2017-08-04 12 views
0

我想根據列名和第一列的值重新塑造數據框。例如,我想這個數據幀重塑:Python根據列名和第一列值重塑

hours mon tue wed 
0  3 4 5 
1  6 7 8 
2  9 10 11 

到下面的數據幀:提前

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 

感謝。

+1

我參觀過這個問題,夫妻的時候,你應該先google一下。 – Wen

回答

2

使用pandas.melt

import pandas as pd 
pd.melt(df, id_vars='hours', var_name='day', value_name='target') 

enter image description here

+1

感謝您的快速回答。我會盡快接受你的回答。 – user3103646

0

我們也可以使用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