0

import pandas as pd

I have the following data frame :

    Col1  Col2
0     a     0
1     b     1
2     a     1
2     b     1
3     a     0
3     c     1

I want to reformate it into :

    newCol_a  newCol_b   newCol_c
0      0         0          0
1      0         1          0
2      1         1          0
3      0         0          1

Basically kind of transposing the two old columns and make Col1 values a list of columns in the new dataframe, with respect to the index value (not unique), the value should default to 0 if the letter is not found (e.g : b and c for index 0).

I am pretty stuck on how to do this

Asddfg
  • 237
  • 3
  • 13

1 Answers1

1

If you add Col1 to the index, you can .unstack() it to convert its values to columns:

In [7]: df.set_index("Col1", append=True)['Col2'].unstack(fill_value=0)
Out[7]:
Col1  a  b  c
0     0  0  0
1     0  1  0
2     1  1  0
3     0  0  1
Randy
  • 14,349
  • 2
  • 36
  • 42