gpt4 book ai didi

python - 在 pandas df 中返回列名称的最有效方法

转载 作者:行者123 更新时间:2023-12-01 01:46:46 25 4
gpt4 key购买 nike

我有一个 pandas df,其中包含 4 个不同的。对于每行都有一个重要的。我想返回显示列名称。因此,对于下面的 df,我想在标记值 2 时返回 Column 名称。

d = ({
'A' : [2,0,0,2],
'B' : [0,0,2,0],
'C' : [0,2,0,0],
'D' : [0,0,0,0],
})

df = pd.DataFrame(data=d)

输出:

   A  B  C  D
0 2 0 0 0
1 0 0 2 0
2 0 2 0 0
3 2 0 0 0

所以它会是A,C,B,A

我通过以下方式执行此操作

m = (df == 2).idxmax(axis=1)[0]

然后更改行。但这效率不高。

我还希望将 pandas df 的输出作为 Series 生成

最佳答案

使用DataFrame.dot:

df.astype(bool).dot(df.columns).str.cat(sep=',')

或者,

','.join(df.astype(bool).dot(df.columns))

'A,C,B,A'

或者,作为列表:

df.astype(bool).dot(df.columns).tolist()
['A', 'C', 'B', 'A']

...或系列:

df.astype(bool).dot(df.columns)

0 A
1 C
2 B
3 A
dtype: object

关于python - 在 pandas df 中返回列名称的最有效方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51238001/

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