Pandas数据帧重塑

2024-04-30 05:19:39 发布

您现在位置:Python中文网/ 问答频道 /正文

获得以下数据帧:

                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

如何将重量和其他列与正确的日期和练习“对齐”?你知道吗


Tags: 数据datevaluebody形式rowpressweight
1条回答
网友
1楼 · 发布于 2024-04-30 05:19:39

您可以首先通过^{}Body Weight (KG)列添加到MultiIndex,然后使用重复的index值调用DataFrame构造函数。你知道吗

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

相关问题 更多 >