Home > Enterprise >  changing format of dataframe
changing format of dataframe

Time:11-17

saying we have a data frame looking like this : with x,y,z the value we are interested in.

        Year1  year2    year3
canada.   x1    x2       x3

shape we have

can we transform it to a data frame 2 looking like the following :

Country  Year  Value
Canada   Year1  x1
Canada   Year2  x2
Canada   Year3  x3

shape wanted

and so on for the other countries. Is there a way to code this transformation ?

Original data look like this:

Thank you so much

CodePudding user response:

here is one way to do it

Assuming, in your given DF, country is an index field

# stack and reindex, then rename the columns
df.stack().reset_index().rename(columns={'level_0': 'Country', 'level_1': 'Year', 0:'Value'})
Country     Year    Value
0   canada.     Year1   x1
1   canada.     year2   x2
2   canada.     year3   x3

if country is not an index then and is instead a column then

df.set_index('country').stack().reset_index().rename(columns={'level_0': 'Country', 'level_1': 'Year', 0:'Value'})
  • Related