您可以使用apply 和axis=1 进行按行处理,然后将每一行与1 进行比较以获得索引值(因为axis=1 每行都转换为具有列索引的Series),它们由,:
s1 = df.apply(lambda x: ','.join(x.index[x == 1]), axis=1)
print (s1)
0 B,E
1 C
2 B,C,D
3 A,E
4 D
dtype: object
另一种解决方案,如果更大DataFrame,则更快。
首先将列格式更改为列表:
print (['{}, '.format(x) for x in df.columns])
['A, ', 'B, ', 'C, ', 'D, ', 'E, ']
类似:
s = np.where(df == 1, ['{}, '.format(x) for x in df.columns], '')
因为1 值被转换为Trues。比较 DataFrame 和 Trues 的值,使用列名的自定义格式:
s = np.where(df, ['{}, '.format(x) for x in df.columns], '')
print (s)
[['' 'B, ' '' '' 'E, ']
['' '' 'C, ' '' '']
['' 'B, ' 'C, ' 'D, ' '']
['A, ' '' '' '' 'E, ']
['' '' '' 'D, ' '']]
最后加入所有行并删除空值:
s1 = pd.Series([''.join(x).strip(', ') for x in s], index=df.index)
print (s1)
0 B, E
1 C
2 B, C, D
3 A, E
4 D
dtype: object
编辑:旧答案另一个更好的解决方案:
s1 = df.eq(1).dot(df.columns + ',').str.rstrip(',')