Home > Blockchain >  mutate a column with column names if it contains 1
mutate a column with column names if it contains 1

Time:10-26

I want to Mutate a column h, which contains respective column names [A,B,C,D] if it contains 1

import pandas as pd
dfz = pd.DataFrame({'A' : [1,0,0,1,0,0],
                    'B' : [1,0,0,1,0,1],
                    'C' : [1,0,0,1,3,1],
                    'D' : [1,0,0,1,0,0]})

dfz['h'] = dfz.loc[:, 'A':'D'].replace(1,pd.Series(dfz.columns,dfz.columns))

Expected output

enter image description here

CodePudding user response:

Use DataFrame.dot with filtered columns and compared values by 1, last use Series.replace with space:

#filtered columns
dfz['h'] = dfz.loc[:, 'A':'D'].eq(1).dot(dfz.loc[:, 'A':'D'].columns).replace('', '0')

#filtered by list
cols = ['A','B','C','D']
dfz['h'] = dfz[cols].eq(1).dot(pd.Index(cols)).replace('', '0')

print (dfz)
   A  B  C  D     h
0  1  1  1  1  ABCD
1  0  0  0  0     0
2  0  0  0  0     0
3  1  1  1  1  ABCD
4  0  0  3  0     0
5  0  1  1  0    BC
  • Related