Home > Software engineering >  Transpose rows to columns while preserving index as it is
Transpose rows to columns while preserving index as it is

Time:03-21

I have the dataset of the following structure:

data = {'Var_name': ['GDP', 'FX', 'Inf'], '2000': [4, 5, 6], '2001': [7, 8, 9], '2002': [10, 11, 12]}
df = pd.DataFrame(data, index=['Country_1', 'Country_1', 'Country_1'])

          Var_name     2000  2001   2002
Country_1   GDP         4     7      10
Country_1   FX          5     8      11
Country_1   Inf         6     9      12

I want to transpose it to the following format:

            Year    GDP FX  Inf
Country_1   2000    4   5   6
Country_1   2001    7   8   9
Country_1   2002    10  11  12

Thank for help in advance.

CodePudding user response:

Use:

df = (df.set_index('Var_name', append=True)
        .stack(0)
        .unstack(1)
        .rename_axis(index=(None, 'Year'), columns=None)
        .reset_index(level=1))
print (df)
           Year  FX  GDP  Inf
Country_1  2000   5    4    6
Country_1  2001   8    7    9
Country_1  2002  11   10   12

CodePudding user response:

You can use .pivot_table

df.pivot_table(index=['Country_1'], columns='Var_name', values='Year',aggfunc='first')

  • Related