1

I have a df with multiple columns. We need to check if any of the columns has a value 0; if 0 is there we have to add new column with tag.

I tried this :

df.loc[df['maths'] == '0', 'mark_student'] = 'fail'

This it working for single column, but when I tried it for multiple columns, it's failing

Like this :

df.loc[df['maths','chemistry'] == '0', 'mark_student'] = 'fail'

df.loc[df[['maths','chemistry']] == '0', 'mark_student'] = 'fail'

2 Answers 2

3

df[['maths','chemistry']] == '0' returns a data frame, which can't be directly used as boolean index at row level. You can use .any(1) to reduce it to a Series and then use it with .loc:

df.loc[(df[['maths','chemistry']] == '0').any(1), 'mark_student'] = 'fail'

Should work.

Sign up to request clarification or add additional context in comments.

Comments

1

You have to use () each condition,

df.loc[(df['maths'] == 0) & (df['chemistry'] ==  0) & (df['mark_student'] == 'fail')

Comments

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.