你可以试试np.where:
import pandas as pd
import numpy as np
df=pd.DataFrame({'a': ['match','mismatch','match'],'b': ['match','match','mismatch'],'c': ['mismatch','mismatch','match']})
print(df)
arr= np.where(df.eq('match'), df.columns, '').sum(axis=1)
print(arr)
输出:
df
a b c
0 match match mismatch
1 mismatch match mismatch
2 match mismatch match
arr
['ab' 'b' 'ac']
然后,要获得所需的列表,您可以尝试:
#first option
arr= np.where(df.eq('match'), df.columns, '').sum(axis=1)
arr=list(map(', '.join,arr))
print(arr)
#second option
arr= np.where(df.eq('match'), df.columns, '').sum(axis=1)
arr=list(map(list,arr))
print(arr)
输出:
#first option
['a, b', 'b', 'a, c']
#second option
[['a', 'b'], ['b'], ['a', 'c']]