Pandas:将列名压缩为单元格值,其中为True

时间:2016-01-22 20:23:59

标签: python pandas dataframe

我的数据框看起来像

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

1 个答案:

答案 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