0

Below is my dataframe.

a b
12 0
1 21
0 0

Now want to add a column name 'c' which return yes when a or b is non-zero and return no when a and b is zero

a b c
12 0 yes
1 21 yes
0 0 no

2 Answers 2

1

If need test all columns compare by 0 and test if all values per row by DataFrame.all with set yes, 'no' by numpy.where:

df['c'] = np.where(df.eq(0).all(axis=1), 'no','yes')

print (df)
    a   b    c
0  12   0  yes
1   1  21  yes
2   0   0   no

Another idea is test if at leastone value is not 0 by DataFrame.any, then is used mapping:

df['c'] = df.ne(0).any(axis=1).map({False: 'no',True:'yes'})

If possible multiple columns and need test only a,b columns:

cols = ['a','b']
df['c'] = np.where(df[cols].eq(0).all(axis=1), 'no','yes')
Sign up to request clarification or add additional context in comments.

Comments

0

Here is the simplest solution I can think of:

import numpy as np
df['c'] = np.where( (df['a']>0) | (df['b']>0), 'yes', 'no')

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.