0

I want to replace some values in my dataframe that meets a condition. I tried to write the code but does not seem working

dfa = df.copy()

for value in df['Clean Company Name']:
    if value=="NaN":
        dfa['Clean Company Name'].replace(df['Company Name'])


dfa.head()

As you can see, the NaN values are not replaced by the 'Company Name'

How do I achieve that result?

1 Answer 1

1

If need replace NaN values need functions combine_first or fillna:

df['Clean Company Name'].combine_first(df['Company Name'])

Or:

df['Clean Company Name'].fillna(df['Company Name'])

Sample:

df = pd.DataFrame({'Company Name':['s','d','f'], 'Clean Company Name': [np.nan, 'r', 't']})
print (df)
  Clean Company Name Company Name
0                NaN            s
1                  r            d
2                  t            f

#if need check NaNs
print (df['Clean Company Name'].isnull())
0     True
1    False
2    False
Name: Clean Company Name, dtype: bool


df['Clean Company Name'] = df['Clean Company Name'].combine_first(df['Company Name'])
print (df)
  Clean Company Name Company Name
0                  s            s
1                  r            d
2                  t            f

More about missing data.

EDIT:

For replace data by condition is possible use loc with boolean mask:

print (df['Company Name'] == 'd')
0    False
1     True
2    False
Name: Company Name, dtype: bool

df.loc[df['Company Name'] == 'd', 'Clean Company Name'] = 'sss'
print (df)
  Clean Company Name Company Name
0                NaN            s
1                sss            d
2                  t            f
Sign up to request clarification or add additional context in comments.

4 Comments

Apparently it does not even recognize if value=="NaN". It never falls in that case
for check NaNs use isnull
Thanks, I still have on doubt: how do I iterate trought the dataframe and change entries in some specific row according to its value? I want to be able to check the value (if statement logic) and take actions accordingly
@Alex - I add another sample, please check it.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.