2

I have a dataframe with values as below:-

data = {'Year': [2010, 2010, 2011, 2011,2012], 'Country': ['Germany', 'France', 'Germany', 'Afghanistan','Kosovo'],'Population':[20000000,30000000,20500000,2000000,60000]}
data_df = pd.DataFrame(data)

The above is just a snippet of the data. The entire dataset has many more years and other countries. All I need is have the below output as per the above:-

Year  Germany    France     Afghanistan Kosovo 
2010 20000000    30000000      NaN       NaN
2011 20500000    NaN           2000000   NaN
2012  NaN        NaN           NaN       60000

The values for the years are unique ones and population values matched as above. If the population does not exist for a certain year that is present, then a NaN will be ideal. How can I transpose columns country and population, leaving just year with its unique values?

I tried the below and it basically transposes every column.

daraframe_transposed = data_df.T
Hummer
  • 429
  • 1
  • 3
  • 16
  • 1
    `data_df.pivot(*df.columns)` should do it. `data_df.pivot(index='Year', columns='Country', values='Population')` – Ch3steR Sep 11 '21 at 11:20

0 Answers0