Pandas how to 'pythonically' reform dataframe so that index is key and dates are columns

Viewed 51

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?

1 Answers

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()
Related