0
    other    x    y    z
1       x  NaN  NaN  NaN
21      z  NaN  NaN  NaN
71      y  NaN  NaN  NaN
2       x  NaN  NaN  NaN
22      z  NaN  NaN  NaN
72      y  NaN  NaN  NaN
3       x  NaN  NaN  NaN
23      z  NaN  NaN  NaN
73      y  NaN  NaN  NaN
60      x  NaN  NaN  NaN
90      z  NaN  NaN  NaN
80      y  NaN  NaN  NaN
91      z  NaN  NaN  NaN
64      x  NaN  NaN  NaN
64      y  NaN  NaN  NaN
155     x  NaN  NaN  NaN
165     y  NaN  NaN  NaN

how to make each entry of 'other' set 1 to the corresponding column and the rest to zero?

mkmostafa
  • 2,673
  • 2
  • 15
  • 35

1 Answers1

4

Another solution would be to use pd.get_dummies. In your case, with the x, y and z columns already existing, you can do:

df[['x', 'y', 'z']] = pd.get_dummies(df.other)

>>> df
    other  x  y  z
1       x  1  0  0
21      z  0  0  1
71      y  0  1  0
2       x  1  0  0
22      z  0  0  1
72      y  0  1  0
3       x  1  0  0
23      z  0  0  1
73      y  0  1  0
60      x  1  0  0
90      z  0  0  1
80      y  0  1  0
91      z  0  0  1
64      x  1  0  0
64      y  0  1  0
155     x  1  0  0
165     y  0  1  0

One nice thing about this is that you don't really have to have your x y z column pre-made (if you don't have them already). Assuming your dataframe was just your other column, you can just do the follwoing, which means if you have any other values besides x, y and z, it will create new "dummy" columns for them too:

df = pd.concat([df, pd.get_dummies(df.other)], axis=1)

Which results in the same final dataframe in your case

sacuL
  • 42,057
  • 8
  • 58
  • 83