如何转置透视表df_pivot,将position维度转为表头?
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:
| team | position | sum points |
|---|---|---|
| Liverpool | fwd | 66.1 |
| Liverpool | gkp | 8.6 |
| Liverpool | mid | 33.9 |
| Liverpool | def | 45.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:
| team | fwd | gkp | mid | def |
|---|---|---|---|---|
| Liverpool | 66.1 | 8.6 | 33.9 | 45.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 pointsteam 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

