1

I am trying to put 0 or 1 in place of the null rows of a column using lambda function, but my code doesn't make any changes in the data.

df[df['a'].isnull()]['a']=df[df['a'].isnull()].apply(lambda x:1 if (x.b==0 and x.c==0) else 
                                                      0,axis=1) 

Where I am wrong in this?? sample table

Akansha
  • 13
  • 3
  • Please add input and output, or at least some toy data – Dani Mesejo Oct 02 '21 at 20:34
  • 1
    `df[df['a'].isnull()]` makes a copy `df[df['a'].isnull()]['a']` accesses the column __in that copy__. Then the copy gets thrown away since there are no references to it any longer [How to deal with SettingWithCopyWarning in Pandas](https://stackoverflow.com/q/20625582/15497888) use `df.loc[df['a'].isnull(), 'a'] = ...` as outlined in the [accepted answer](https://stackoverflow.com/a/20627316/15497888) – Henry Ecker Oct 02 '21 at 20:36

1 Answers1

1

You can use loc to specifically fill the null value rows in your DataFrame. When you're using the apply method you can use it on the entire DataFrame, you do not need to filter for NULL values there. The loc will take care of only filling the rows which meet the NULL condition. This should work :

df['a'].loc[df['a'].isnull()] = df.apply(lambda x:1 if (x.b==0 and x.c==0) else 
                                                  0,axis=1)
Shivam Roy
  • 1,961
  • 3
  • 10
  • 23
  • 1
    In this code only null values are treated and stored in new_df, but then how should I put these replaced values back in my original data frame i.e df ?? – Akansha Oct 02 '21 at 21:26
  • @Akansha I have edited my answer and tested it. Hope it works for you. – Shivam Roy Oct 02 '21 at 22:09