0

See picture attached for what I'm trying to accomplish. I have no problem melting over one column, but as soon as I try to loop, it breaks.

df = pd.DataFrame({'Group':['A','B','C'],'2002':[1,2,7],'2013':[3,4,8],'2016':[5,6,9]})

columns = df.columns
final_list = []

for Year in range(len(columns)):
   list = df.melt(id_vars = ['Group'], value_vars = columns[Year])
   final_list.append(list)

final_list

Get an error that Data needs to be 1-dimensional.

Data

chicagobeast12
  • 643
  • 1
  • 5
  • 20
  • if You are working already on dataframe `df` You may paste result of `df.to_dict()` for reproducibility. – ipj Aug 11 '20 at 12:45

1 Answers1

1

Here's a way to do that. No need for a loop:

df.melt(id_vars="Group", var_name="year").sort_values("Group")

The output is:

  Group  year  value
0     A  2002      1
3     A  2013      3
6     A  2016      5
1     B  2002      2
4     B  2013      4
7     B  2016      6
2     C  2002      7
5     C  2013      8
8     C  2016      9
Roy2012
  • 11,755
  • 2
  • 22
  • 35