You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何转置透视表df_pivot,将position维度转为表头?

Reshape Pivot Table to Wide Format

Got it, let's fix this pivot table reshaping for you. Here are two straightforward ways to get the exact format you want using pandas:

Method 1: Use pivot() (for long-format input)

If your current df_pivot is in a long format like this:

teampositionsum points
Liverpoolfwd66.1
Liverpoolgkp8.6
Liverpoolmid33.9
Liverpooldef45.2

Run this code to convert it to the wide format you need:

# Pivot the table: team as rows, position as columns, sum points as values
df_transposed = df_pivot.pivot(index='team', columns='position', values='sum points').reset_index()

# Clean up the column names (remove the 'position' header label)
df_transposed.columns.name = None

This will output exactly the structure you asked for:

teamfwdgkpmiddef
Liverpool66.18.633.945.2

Method 2: Use unstack() (if your pivot already has a multi-index)

If your df_pivot has a multi-index (with team as the top-level index and position as the second), like this:

sum points

team position
Liverpool fwd 66.1
gkp 8.6
mid 33.9
def 45.2

Use unstack() to move the position index level into columns:

# Unstack the position index to columns
df_transposed = df_pivot.unstack(level='position').reset_index()

# Flatten the multi-level column names
df_transposed.columns = ['team'] + [col[1] for col in df_transposed.columns[1:]]
df_transposed.columns.name = None

Either method will get you the table format where team is a row and fwd/gkp/mid/def are the column headers.

内容的提问来源于stack exchange,提问作者8-Bit Borges

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.09 06:17:52