-2

I got a dataframe like this:

A B C
1 1 1
2 2 2
3 3 3
4 1 1

I want to 'merge' the three columns to form a D column, the rule is: if there is at least one '1' in the row, then the value of D is '1' else is '0'. How can I achieve it?

Lilian417
  • 59
  • 7

1 Answers1

1

Use DataFrame.eq for compare values with DataFrame.any for check at least one True per row and last cast boolean mask to integers:

df['D'] = df.eq(1).any(axis=1).astype(int)
print (df)
   A  B  C  D
0  1  1  1  1
1  2  2  2  0
2  3  3  3  0
3  4  1  1  1

Detail:

print (df.eq(1))
       A      B      C
0   True   True   True
1  False  False  False
2  False  False  False
3  False   True   True

print (df.eq(1).any(axis=1))
0     True
1    False
2    False
3     True
dtype: bool
jezrael
  • 822,522
  • 95
  • 1,334
  • 1,252