可以通过行使用apply
与axis=1
进行处理,然后比较各行与1
为索引值(因为axis=1
每一行被转换成系列与来自列索引),其通过,
接合:
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
值被强制转换为True
秒。比较DataFrame
值和列名的True
的使用自定义格式:
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
答案是向下:) – amn89
伟大的工作agaim,@jezrael – pyd
重复的https://stackoverflow.com/questions/32125954/pandas-map-0-1-data-frame-entries-to-column-names和https://stackoverflow.com/questions/38169342/python-pandas -dataframe-return-column-name – Zero