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

如何在Python中对Pandas DataFrame分组后转置指定行列?

Pandas分组后转置指定行列的实现思路

问题背景

尝试对Pandas DataFrame进行分组,并转置其中的单一列或单一行,已使用GroupBy和Pivot函数,寻求可行实现方案。

示例数据与当前代码:

import pandas as pd

name = 'Name'
account = 'Account'
price = 'Price'
date = 'Date'
month = 'Month'

dictionary = {
  name: 
      ['aaa','aaa','bbb','bbb','bbb','ccc','ccc','ccc'],
  account: 
      [22, 33, 22, 22, 33, 12, 12, 10],
  price: 
      [100, 345, 345, 667, 1_033, 234, 10, 12],
  date: 
      ['01-05-2022', '02-06-2022', '04-04-2022', '23-01-2022', '01-05-2022', '02-02-2022', '04-02-2022', '23-01-2022']
}

df = pd.DataFrame(data=dictionary)

df[date] = pd.to_datetime(df[date], format='%d-%m-%Y')
df[month] = pd.DatetimeIndex(df[date]).month

group = df.groupby([month, name]).agg({price:['count', 'sum']})

group.transpose()

实现思路

1. 调整GroupBy结果的层级后转置

当前group.transpose()会转置所有索引层级,若需精准控制行列映射,可先重置索引再用pivot重塑结构:

# 重置索引,将分组键转为普通列
group_reset = group.reset_index()
# 重塑表格:Name为行,Month为列,聚合指标为值
result = group_reset.pivot(index=name, columns=month, values=[(price, 'count'), (price, 'sum')])
# 调整列层级顺序,让Month排在聚合指标前
result = result.swaplevel(axis=1).sort_index(axis=1)
print(result)

2. 直接用pivot_table一步生成目标结构

跳过先分组再转置的步骤,直接通过pivot_table指定行、列、聚合函数:

result = pd.pivot_table(df, 
                        index=name, 
                        columns=month, 
                        values=price, 
                        aggfunc=['count', 'sum'],
                        fill_value=0)  # 填充缺失组合的空值为0
# 调整列层级,优化展示顺序
result = result.swaplevel(axis=1).sort_index(axis=1)
print(result)

3. 转置单一列/行

如果仅需转置某一列(比如Price的sum列):

# 提取目标列并转置
sum_transposed = group[(price, 'sum')].to_frame().transpose()
print(sum_transposed)

如果仅需转置某一行(比如Month=1、Name='bbb'的行):

# 提取目标行并转置
row_transposed = group.loc[(1, 'bbb')].to_frame().transpose()
print(row_transposed)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.17 14:25:24