i have a data frame
JavaScript
x
6
1
A B C
2
True False False
3
False False True
4
True False False
5
False False False
6
I want to get column named “result” which will return the column name if it is true and nan, if any of it is not True.
Expected Column
JavaScript
1
6
1
result
2
A
3
C
4
A
5
na
6
Advertisement
Answer
You could use Series.where
to set the column value to either the idxmax
along the second axis, so the respective column name of the first True
, or NaN
, depending on the result of df.any(1)
:
JavaScript
1
2
1
df['result'] = df.idxmax(1).where(df.any(1))
2
Or for a numpy
based one you can use argmax
instead:
JavaScript
1
4
1
import numpy as np
2
3
df['result'] = np.where(df.values.any(1), df.columns[df.values.argmax(1)], np.nan)
4
JavaScript
1
8
1
print(df)
2
3
A B C result
4
0 True False False A
5
1 False False True C
6
2 True False False A
7
3 False False False NaN
8