i具有以下数据框架
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,该DF返回每个行的列值" 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
如果多个True
S:
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