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?
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?
Use DataFrame.eq
for compare values with DataFrame.any
for check at least one True
per row and last cast boolean mask to integer
s:
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