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

如何在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.
typeqtvol
-----------
A110
A212
A112

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 as NaN if you need to keep the data structured for further processing.

内容的提问来源于stack exchange,提问作者Boris

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.11 08:16:13