2

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

2
  • Please add input and output, or at least some toy data Commented Oct 2, 2021 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 use df.loc[df['a'].isnull(), 'a'] = ... as outlined in the accepted answer Commented Oct 2, 2021 at 20:36

1 Answer 1

2

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)
Sign up to request clarification or add additional context in comments.

2 Comments

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 I have edited my answer and tested it. Hope it works for you.

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.