0

In Python, I have the following dataframe:

df_dict = {'time':[1,2,3],'a':['a1','a2','a3'],'b':['b1','b2','b3'], 'c':['c1','c2','c3']}

df = pd.DataFrame(df_dict)

df

  time  a   b   c
0   1   a1  b1  c1
1   2   a2  b2  c2
2   3   a3  b3  c3

I need to add a new column which takes value from columns a, b , c and become like this:

   time   new_column   values
0   1        a           a1
1   2        a           a2
2   3        a           a3
3   1        b           b1
4   2        b           b2
5   3        b           b3
6   1        c           c1
7   2        c           c2
8   3        c           c3

Basically, the values in column 'time' is repeated. I need help with the Python code please. And what is the technical term for this action? Very much appreciated.

  • this looks like pandas [melt](https://pandas.pydata.org/docs/reference/api/pandas.melt.html). Try df.melt('time') – sammywemmy Apr 06 '20 at 03:00

1 Answers1

2

Use df.melt

In [3]: df.melt(id_vars='time', value_vars=['a', 'b', 'c'])                                                              
Out[3]: 
   time variable value
0     1        a    a1
1     2        a    a2
2     3        a    a3
3     1        b    b1
4     2        b    b2
5     3        b    b3
6     1        c    c1
7     2        c    c2
8     3        c    c3
Eric Truett
  • 2,970
  • 1
  • 16
  • 21