How can I map the headers to columns in pandas?

前端 未结 5 1572
隐瞒了意图╮
隐瞒了意图╮ 2020-12-16 01:15

I have a dataframe like :

A    B    C 
1    0    0
1    1    0
0    1    0
0    0    1

I want to have :

 A    B    C  lab         


        
5条回答
  •  春和景丽
    2020-12-16 01:48

    In [101]: df['label'] = df.apply(lambda x: ''.join(df.columns[x.astype(bool)].tolist()), axis=1)
    
    In [102]: df
    Out[102]:
       A  B  C label
    0  1  0  0     A
    1  1  1  0    AB
    2  0  1  0     B
    3  0  0  1     C
    

    PS i would definitely chose @Ted's solution as it's much nicer and much much much ... faster

提交回复
热议问题