python - 检查 pandas 行中是否存在值,如果存在,在哪些列中

标签 python pandas dataframe

我正在遍历 pandas DataFrame 的行,如下所示:

         col0      col1      col2
0       False     False     False
1       False     False      True
2       False      True     False
3       False      True      True
4        True     False     False
5        True     False      True
6        True      True     False
7        True      True      True
8       False      True      True
9        True      True     False

我想要一种方法,为每一行获取为真的列的列号:

所以在这里,输出看起来像这样:

1 col2
2 col1
3 col1
3 col2
4 col0
5 col0
5 col2
6 col0
6 col1
7 col0
7 col1
7 col2
8 col1
8 col2
9 col0
9 col1

最佳答案

通过使用mul

df.mul(df.columns).replace('',np.nan).stack().reset_index(level=1,drop=True)
Out[122]: 
1    col2
2    col1
3    col1
3    col2
4    col0
5    col0
5    col2
6    col0
6    col1
7    col0
7    col1
7    col2
8    col1
8    col2
9    col0
9    col1
dtype: object

来自 piR

df.mul(df.columns).where(df).stack().reset_index(level=1, drop=True)

关于python - 检查 pandas 行中是否存在值,如果存在,在哪些列中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48198953/

相关文章:

python - 值错误 : Must have equal len keys and value when setting with an iterable when inserting a list

python - 如何在 ipython 中将 Spark RDD 转换为 pandas 数据帧?

python - 长时间运行的进程中的 SQLAlchemy session 管理

python - 是否可以添加带有列表理解的 where 子句?

python - 有没有办法根据斯坦福 NLP 研究论文在 scikit-learn 多项式朴素贝叶斯中提取最大后验概率?

python - Pandas:如何检查列表类型的列是否在数据框中

python - 如何按列值对 python pandas 数据帧进行分位数,然后对每个分位数求和?

python - pandas 数据框中过滤列表时出错

python - 根据列中的值过滤 pandas 数据框中的行

python - 使用列表元素进行正则表达式搜索以在大型文档中查找匹配项