gpt4 book ai didi

pandas - 使用 boolean 检查返回数据框中的列名

转载 作者:行者123 更新时间:2023-12-02 06:50:26 24 4
gpt4 key购买 nike

我有以下带有 boolean 值的数据框

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,它为每一行返回列值 '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

关于pandas - 使用 boolean 检查返回数据框中的列名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45974715/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com