简体   繁体   English

从DataFrame中按行提取列名称到Series

[英]Row-wise extract column names from DataFrame into Series

I'd like to extract the column names in a list to a Series filtered on the values in each row 我想将列表中的列名提取到按每行值过滤的Series

In [1]: import pandas as pd   

In [2]: df =pd.DataFrame({'colA':[1,0,1], 'colB':[0,0,1], 'colC':[1,0,0]})    

In [3]: print(df)

   colA  colB  colC
0     1     0     1
1     0     0     0
2     1     1     0

The resulting Series should look like this: 生成的系列应如下所示:

0    [colA, colC]
1              []
2    [colA, colB]
dtype: object

Here's the tortured solution I came up with: 这是我想出的折磨解决方案:

In [4]: df2 = df.T

In [5]: l = [df2[df2[i]>0].index.values.tolist() for i in range(3)]

In [6]: print(pd.Series(l))

0    [colA, colC]
1              []
2    [colA, colB]
dtype: object

Is there a less tortured way of doing this? 有没有那么折磨的方式呢?

You could use np.where assuming your dataframe is constituted by 0's and 1's, and create a Series from the result: 您可以使用np.where假设您的数据帧由0和1组成,并根据结果创建一个Series:

x = np.where(df,df.columns,'')
pd.Series([' '.join(i).split() for i in x])
0    [colA, colC]
1              []
2    [colA, colB]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM