我的数据框看起来像
ID Cat1 Cat2 Cat3 Cat4
3432432 True False True False
1242323 False True False False
3423883 False False False True
如何将其转换为选择第一列为True的数据框?
ID Status
3432432 Cat1
1242323 Cat2
3423883 Cat4
答案 0 :(得分:8)
您可以利用idxmax
将返回第一个True的事实:
>>> df.set_index("ID").idxmax(axis=1).reset_index(name="Status")
ID Status
0 3432432 Cat1
1 1242323 Cat2
2 3423883 Cat4
因为我们有
而有效>>> df.iloc[:,1:]
Cat1 Cat2 Cat3 Cat4
0 True False True False
1 False True False False
2 False False False True
>>> df.iloc[:,1:].idxmax(axis=1)
0 Cat1
1 Cat2
2 Cat4
dtype: object