Return Dataframe 中带有布尔检查的列名

Return column name in Dataframe with boolean check

我有以下带布尔值的数据框

Out[25]: 
                0     1      2
Date                          
2007-01-03  False  True  False
2007-01-04  False  False True
2007-01-05  False  True  False
2007-01-08  True   False False
2007-01-09  False  True  False

我正在寻找一个 DF,其中 returns 每行的列值 'True' 的列索引。

所需输出:

            0
Date                          
2007-01-03  1
2007-01-04  2
2007-01-05  1
2007-01-08  0
2007-01-09  1

最好的 pythonic 方法是什么?

如果每行只有一个 True 使用 idxmax:

df['new'] = df.idxmax(axis=1)
print (df)
                0      1      2 new
Date                               
2007-01-03  False   True  False   1
2007-01-04  False  False   True   2
2007-01-05  False   True  False   1
2007-01-08   True  False  False   0
2007-01-09  False   True  False   1

如果多个Trues:

df['new'] = df.apply(lambda x: ','.join(x.index[x]), axis=1)
print (df)
                0      1      2  new
Date                                
2007-01-03  False   True   True  1,2
2007-01-04  False  False   True    2
2007-01-05  False   True  False    1
2007-01-08   True  False  False    0
2007-01-09  False   True  False    1

另一个解决方案:

print (['{}, '.format(x) for x in df.columns])
['0, ', '1, ', '2, ']

s = np.where(df, ['{}, '.format(x) for x in df.columns], '')
df['new'] = pd.Series([''.join(x).strip(', ') for x in s], index=df.index)
print (df)
                0      1      2   new
Date                                 
2007-01-03  False   True   True  1, 2
2007-01-04  False  False   True     2
2007-01-05  False   True  False     1
2007-01-08   True  False  False     0
2007-01-09  False   True  False     1