Reputation: 23
I would like to reshape a data frame according to column names and first column's value. For example, I want to reshape this data frame:
hours mon tue wed
0 3 4 5
1 6 7 8
2 9 10 11
into following data frame:
hours day target
0 mon 3
1 mon 6
2 mon 9
0 tue 4
1 tue 7
2 tue 10
0 wed 5
1 wed 8
2 wed 11
Thanks in advance.
Upvotes: 0
Views: 220
Reputation: 210882
We can also use pd.lreshape
:
In [118]: cols = df.columns.drop('hours').tolist()
In [119]: pd.lreshape(df, {'target':cols}).assign(day=np.repeat(cols, len(df)))
Out[119]:
hours target day
0 0 3 mon
1 1 6 mon
2 2 9 mon
3 0 4 tue
4 1 7 tue
5 2 10 tue
6 0 5 wed
7 1 8 wed
8 2 11 wed
Upvotes: 0
Reputation: 215047
Use pandas.melt
:
import pandas as pd
pd.melt(df, id_vars='hours', var_name='day', value_name='target')
Upvotes: 2