python - 按行将列名从 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
有没有一种不那么折磨人的方式来做到这一点?
解决方案
您可以使用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]
推荐阅读
- r - AVE vs MAX 数据使用和要求?
- c++ - 模板化的类和友元函数
- node.js - Nest.js 框架热重载不起作用
- django - Django-过滤一个或多个反向外键符合条件的结果
- batch-file - 任务计划程序运行批处理文件 - 批处理文件仅部分工作?
- api - PowerShell HTTPIE
- hibernate - 使用带有查询注释 Spring Data JPA 的分页时出错
- python - pyspark 中的单热编码,连续多个 1
- python - Python 如何读取 .txt 文件中的行并将它们拆分为列表?
- matlab - 在 Matlab 中从 Gumbel 分布中绘制随机数