首页 > 解决方案 > 按行将列名从 DataFrame 提取到 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

生成的系列应如下所示:

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

这是我想出的折磨解决方案:

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

有没有一种不那么折磨人的方式来做到这一点?

标签: pythonpandas

解决方案


您可以使用np.where假设您的数据框由 0 和 1 组成,并根据结果创建一个系列:

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

推荐阅读