PPP
PPP

Reputation: 213

Groupby or Transpose?

I got this data

    country                     report_date market_cap_usd
0   Australia                   6/3/2020    90758154576
1   Australia                   6/4/2020    91897977251
2   Australia                   6/5/2020    94558861975
3   Canada                      6/3/2020    42899754234
4   Canada                      6/4/2020    43597908706
5   Canada                      6/5/2020    45287016456
6   United States of America    6/3/2020    1.16679E+12
7   United States of America    6/4/2020    1.15709E+12
8   United States of America    6/5/2020    1.19652E+12

and want to turn it into:

report_date Australia Canada ....
6/3/2020 90758154576 42899754234 ...
6/4/2020 91897977251 43597908706 ...

How can I do this?

Upvotes: 0

Views: 35

Answers (1)

Sy Ker
Sy Ker

Reputation: 2190

Use pivot_table;

# setting minimum example 
import pandas

data = pandas.DataFrame({'country': ['Australia', 'Australia', 'Canada', 'Canada'], 
              'report_data': ['6/3/2020', '6/4/2020', '6/3/2020', '6/4/2020'], 
              'market_cap_usd': [923740927, 92797294, 20387334, 392738092] 
             })
# pivot the table
data = data.pivot_table(index='report_data', columns='country')

# drop multi-index column 
data.columns = [col[1] for col in data.columns]

Output;

            Australia   Canada
report_data         
6/3/2020    923740927   20387334
6/4/2020    92797294    392738092

Upvotes: 1

Related Questions