在pandas df中返回列名称的最有效方法 [英] Most efficient way to return Column name in a pandas df

查看:144
本文介绍了在pandas df中返回列名称的最有效方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个pandas df,其中包含4个不同的columns.对于每个row,都有一个value重要.我想返回显示valueColumn name.因此,对于下面的df,我想在标记值为2时返回Column名称.

I have a pandas df that contains 4 different columns. For every row theres a value thats of importance. I want to return the Column name where that value is displayed. So for the df below I want to return the Column name when the value 2 is labelled.

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]

然后更改行.但这不是很有效.

And then changing the row. But this isn't very efficient.

我也希望从pandas df

推荐答案

使用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

这篇关于在pandas df中返回列名称的最有效方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆