changing format of dataframe

Question:

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

Asked By: Aroune

||

Answers:

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'})
Answered By: Naveed
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.