1

I have a pandas DataFrame and I want to reshape it.

  Country       1991  1992  1993  
Deutschland      1     2     3
Griechenland     4     7     0

How to make a new DataFrame that looks like this:

      Country       Year   Value
    Deutschland     1991     1
    Deutschland     1992     2
    Deutschland     1993     3
    Griechenland    1991     4
    Griechenland    1992     7
    Griechenland    1993     0
Sinchetru
  • 539
  • 1
  • 3
  • 13

1 Answers1

4

Using melt (and then sorting the values by country and year and resetting the index):

(df.melt('Country', var_name='Year', value_name='Value')
   .sort_values(['Country', 'Year'])
   .reset_index(drop=True))

Output:

        Country  Year  Value
0   Deutschland  1991      1
1   Deutschland  1992      2
2   Deutschland  1993      3
3  Griechenland  1991      4
4  Griechenland  1992      7
5  Griechenland  1993      0
perl
  • 9,826
  • 1
  • 10
  • 22