0

I have a dataframe looks like below:

   date       A       B       C
2015-01-25  0.97    0.33    0.65
2015-02-01  0.23    0.02    0.67

My goal is to covert the df to a new format like below:

  date     Type Value
2015-01-25  A   0.97
2015-02-01  A   0.23
2015-01-25  B   0.33
2015-02-01  B   0.08
2015-01-25  C   0.65
2015-02-01  C   0.67

which means move all the columns to the rows as a new column as type, and put their value for each date as a unique columns, I did some search on Google, but still cannot find a right solution.

Can anyone please help?

Worst SQL Noob
  • 189
  • 1
  • 5
  • 15

2 Answers2

1

You can use pandas.melt() method like this:

>>> df = df.melt(id_vars=['date'], var_name='Type', value_name='Value')
>>> print(df)
         date Type  Value
0  2015-01-25    A   0.97
1  2015-02-01    A   0.23
2  2015-01-25    B   0.33
3  2015-02-01    B   0.02
4  2015-01-25    C   0.65
5  2015-02-01    C   0.67
Jaroslav Bezděk
  • 6,967
  • 6
  • 29
  • 46
1

Use melt()

df.melt(id_vars='date', var_name='Type', value_name='Values')
Peter
  • 10,959
  • 2
  • 30
  • 47