1

Take a dataframe as follows


df = pd.DataFrame({'Key': ['0', '0', '0', '1', '1',
                           '1'],
                   'Dt': ['2021-08-01', '2021-08-02', '2021-08-03', '2021-08-01', '2021-08-02', '2021-08-03'],
                   'val': [1, 2, 3, 4, 5, 6]})

and convert to dataframe that looks like the following

Key 2021-08-01 2021-08-02 2021-08-03
0 1 2 3
1 4 5 6

I can see how to manually do this in a loop but is there a quicker more 'pythonic' way to do this?

amstergc20
  • 117
  • 1
  • 11

1 Answers1

1

IIUC, you can try:

df.pivot(*df)

OUTPUT:

Dt   2021-08-01  2021-08-02  2021-08-03
Key                                    
0             1           2           3
1             4           5           6

Alternative set_index & unstack option -

df.set_index(['Key', 'Dt']).unstack()
Nk03
  • 14,699
  • 2
  • 8
  • 22
  • Please avoid the `*df` "trick", it only works if there are 3 columns in the correct order, it is not generalizable nor good practice – mozway Dec 04 '21 at 16:10