Consolidate and show all the occurrences based on date and country

Question:

So I have a dataframe like that

Date        | Country | Occurrences
2021-08-25  |   CA    |     188
2021-08-25  |   AE    |     10
2021-08-25  |   BE    |     25
2021-08-25  |   GR    |     49
2021-08-26  |   CA    |     200
2021-08-26  |   AE    |     7
2021-08-26  |   BE    |     27
2021-08-25  |   GR    |     52

and I want to show it like this

Date        | CA  | AE | BE | GR
2021-08-25  | 188 | 10 | 25 | 49
2021-08-25  | 200 | 7  | 27 | 52

How do I go about doing it? I tried df.explode('Country') but it did not take into consideration the occurrences

Asked By: Aaron

||

Answers:

Try using df.pivot_table().

data = {'Date': ['2021-08-25', '2021-08-25', '2021-08-25', '2021-08-25', '2021-08-26', '2021-08-26', '2021-08-26', '2021-08-25'],
        'Country': ['CA', 'AE', 'BE', 'GR', 'CA', 'AE', 'BE', 'GR'],
        'Occurrences': [188, 10, 25, 49, 200, 7, 27, 52]}
df = pd.DataFrame(data)
pivot_df = df.pivot_table(index='Date', columns='Country', values='Occurrences')
Answered By: beh aaron
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.