Python 检查行中是否存在值,如果存在,则检查哪些列中的值

Python 检查行中是否存在值,如果存在,则检查哪些列中的值,python,pandas,dataframe,Python,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

我在熊猫数据帧的行上进行迭代,如下所示:

         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)

使用
np.where

i, j = np.where(df)
pd.Series(df.columns[j], df.index[i])

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

我找到了一种方法,看起来很难看,但是嘿
\_(ツ)_/“

for rownumber, values in my_dataframe.iterrows():
    for colnumber, value in enumerate(list(values)):
        if value == True:
            print(rownumber, my_dataframe.columns[colnumber])

这里可以使用列表理解,将列名列表和df值作为列表列表:

outlist = [ [i, df.columns.tolist()[j]]
        for i,r in enumerate(df.values)
        for j,c in enumerate(r)
        if c ]

print(outlist)
输出:

[[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']]

另外,添加这个。
df.mul(df.columns)。where(df.stack().reset_index(level=1,drop=True)
@piRSquared是的!!忘记面具(where)不知道为什么你输了一次向上投票!这是一个非常好的答案。@piRSquared没问题:-)我为你的努力鼓掌,但这是一个不必要的双环,有些人会认为它与大熊猫背道而驰。