2017-09-25 189 views
1

得到了以下數據幀:熊貓數據幀重塑

   Body Weight (KG) Exercise 1 Weight (KG) Exercise 2 \ 
Date                
17/07/17    77.9  Squat    20.0  Bench Press 

       Weight (KG).1 Exercise 3 Weight (KG).2 
Date             
17/07/17   20.0   Barbell Row   30.0 

試圖重塑成整齊格式:

Date  Body Weight Exercise  Weight 
17/07/17 77.9  Squat  20.0 
17/07/17 77.9  Bench Press 20.0 
17/07/17 77.9  Barbell Row 30.0 

使用熔體函數嘗試使用

pd.melt(df,value_vars=["Exercise 1","Exercise 2","Exercise 3"]) 

導致:

variable  value 
0 Exercise 1  Squat 
1 Exercise 2  Bench Press 
2 Exercise 3  Barbell Row 

我如何獲得重量和其他列「排隊」與正確的日期和鍛鍊?

+0

'打印(df.head(10).to_dict())'和粘貼在這裏輸出請,這是不可能的現在就複製你的DF。 –

+0

{'重量(KG)':{'17/07/17':20.0},'重量(KG).1':{'17/07/17':20.0}'重量(KG).2' :{'17/07/17':30.0},'體重(KG)':{'17/07/17':77.900000000000006},'練習1':{'17/07/17' },'練習2':{'17/07/17':'Bench Press'},'練習3':{'17/07/17':'Barbell Row'}} –

回答

1

您可以先通過set_index添加Body Weight (KG)MultiIndex,然後調用構造函數DataFrame與重複index值。

Notice - 需要對ExerciseWeight所有列,而不先爲正確的輸出

df = df.set_index('Body Weight (KG)', append=True) 
a = len(df.index) 
b = int(len(df.columns)/2) 
df = pd.DataFrame(df.values.reshape(a * b ,2), 
        index=df.index.repeat(b), 
        columns=['Exercise', 'Weight']).reset_index() 
print (df) 
     Date Body Weight (KG)  Exercise Weight 
0 17/07/17    77.9  Squat  20 
1 17/07/17    77.9 Bench Press  20 
2 17/07/17    77.9 Barbell Row  30 
+0

謝謝,究竟需要什麼。 –