我正在遍历 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/