Roy Devjyoti
Roy Devjyoti

Reputation: 127

How to replace the values of 1's and 0's of various column into a single column of a data frame?

The 0's and 1's need to be transposed to there appropriate headers in python. How can I achieve this and get the column final_list?columns for different verticals

Upvotes: 1

Views: 30

Answers (1)

jezrael
jezrael

Reputation: 862511

If there is always only one 1 per rows use DataFrame.dot:

df = pd.DataFrame({'a':[0,1,0],
                   'b':[1,0,0],
                   'c':[0,0,1]})

df['Final'] = df.dot(df.columns)
print (df)
   a  b  c Final
0  0  1  0     b
1  1  0  0     a
2  0  0  1     c

If possible multiple 1 also add separator and then remove it by Series.str.rstrip from output Series:

df = pd.DataFrame({'a':[0,1,0],
                   'b':[1,1,0],
                   'c':[1,1,1]})

df['Final'] = df.dot(df.columns + ',').str.rstrip(',')
print (df)
   a  b  c  Final
0  0  1  1    b,c
1  1  1  1  a,b,c
2  0  0  1      c

Upvotes: 2

Related Questions