如何在Pandas DataFrame中实现分组数据的横向转置?
Hey there! Let's figure out how to rearrange your DataFrame into that grouped horizontal layout you want. Using pandas, we can break this down into simple, actionable steps:
Step 1: Set up your original DataFrame
First, let's recreate your initial dataset (skip this if you already have your DataFrame loaded):
import pandas as pd df = pd.DataFrame({ 'type': ['A', 'A', 'A', 'B', 'B', 'B', 'C', 'C', 'C', 'C'], 'qt': [1, 2, 1, 3, 4, 4, 4, 4, 4, 4], 'vol': [10, 12, 12, 11, 20, 20, 20, 20, 20, 20] })
Step 2: Process groups and align rows
We'll split the DataFrame by type, adjust each group's columns to include the type prefix, then stitch them together horizontally:
# Split into groups by 'type' and process each one grouped_dfs = [] for group_name, group_data in df.groupby('type'): # Reset index to ensure rows align perfectly across different groups group_reset = group_data.reset_index(drop=True) # Rename columns to add the group prefix (e.g., "A.type" instead of just "type") group_reset.columns = [f"{group_name}.{col}" for col in group_reset.columns] grouped_dfs.append(group_reset) # Combine all groups side-by-side, filling empty cells with blank strings final_df = pd.concat(grouped_dfs, axis=1).fillna('')
Step 3: Get the exact Markdown table layout
Pandas doesn't natively support merged header cells, but we can manually format the result to match your desired table:
| A. | B. | C. |
|---|---|---|
| type | qt | vol |
| ---- | ---- | --- |
| A | 1 | 10 |
| A | 2 | 12 |
| A | 1 | 12 |
Quick Explanation:
reset_index(drop=True)makes sure each group's rows start at index 0, so shorter groups (like A and B) will have blank cells where longer groups (like C) have extra entries.- Using
fillna('')replaces missing values with empty strings to match your example, but you can leave them asNaNif you need to keep the data structured for further processing.
内容的提问来源于stack exchange,提问作者Boris
相关产品推荐
相关产品推荐

