0

I currently have a Data Frame that looks like so when I read it in:

Date Country A B C
01/01/2020 AFG 0 1 5
01/02/2020 AFG 2 5 0
01/03/2020 AFG 1 4 1
... ... ... ... ...
01/01/2020 USA 2 3 7
01/02/2020 USA 4 5 6

I would like to transform it into the form below, whereby the country becomes the row's index, date replaces the columns, and the values of Column A go onto fill the date's respective value for each country.

Country 01/01/2020 01/02/2020 01/03/2020 ... 04/25/2021
AFG 0 2 1 ... 5
USA 2 4 9 ... 15

I have tried to use group-by before but nothing appears to be working quite in the way shown above. Am I forgetting a command or is there some way this can be done?

1 Answers1

1

You can do it in this way:

  1. TRY pivot_table to get the required.

  2. Use rename_axis to remove the axis name.

  3. Finally reset the index via reset_index().

df = df.pivot_table(index='Country', columns='Date', values='A', fill_value=0).rename_axis(None, axis=1).reset_index()

OUTPUT:

  Country  01/01/2020  01/02/2020  01/03/2020
0     AFG           0           2           1
1     USA           2           4           0
Nk03
  • 14,699
  • 2
  • 8
  • 22