Pandas转变

2024-06-26 13:15:17 发布

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

假设我有以下数据帧:

metric  value   last_1_day  last_7_day
points  10  3   9
assists 15  2   12
rebounds    12  1   5

我想转置它,并将度量中的thre值和其他列连接起来。因此,结果将有1行9列。例如:

points_value    points_last_1_day   points_last_7_day   assists_value   assists_last_1_day  assists_last_7_day  rebounds_value  rebounds_last_1_day rebounds_last_7_day
10  3   9   15  2   12  12  1   5

在熊猫身上这样做的最佳方式是什么


Tags: 数据度量value方式metricpointslastday
1条回答
网友
1楼 · 发布于 2024-06-26 13:15:17

尝试:

df = df.set_index('metric').stack().to_frame().T
df.columns = ['_'.join(a) for a in df.columns]

输出:

   points_value  points_last_1_day  points_last_7_day  assists_value  assists_last_1_day  assists_last_7_day  rebounds_value  rebounds_last_1_day  rebounds_last_7_day
0            10                  3                  9             15                   2                  12              12                    1                    5

相关问题 更多 >