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

Pandas对DataFrame数据排序分箱后生成指定聚合透视表方法

实现方案

直接使用pandas内置的pivot_table方法即可完成需求,不需要编写自定义分组逻辑,操作步骤如下:

  • 导入pandas库,基于提供的字段构造原始DataFrame
  • 调用透视表方法时,明确指定行索引、列字段、聚合取值字段、聚合规则即可
import pandas as pd

# 构造原始数据集
Height = [1, 4, 3, 3, 3, 2, 4, 2, 3, 3, 3, 1, 4, 3, 3, 4, 1, 4, 2, 2]
Period = [5, 4, 2, 4, 2, 2, 3, 3, 5, 2, 4, 5, 4, 2, 4, 4, 3, 5, 4, 3]
Zone = [1,1,3,1,4,1,1,1,1,4,1,3,2,1,4,2,4,4,2,4]
Direction = [292.5,  22.5, 202.5, 337.5, 292.5, 337.5, 337.5, 337.5,  22.5, 292.5,  22.5, 157.5, 112.5, 337.5, 292.5, 112.5, 247.5, 247.5,
       112.5, 292.5]

df = pd.DataFrame({
    'Height': Height,
    'Period': Period,
    'Zone': Zone,
    'Direction': Direction
})

# 生成目标透视表
result = pd.pivot_table(
    df,
    index="Zone",
    columns="Period",
    values="Height",
    aggfunc="max"
)

运行代码后得到的输出如下,完全匹配需求:

Period    2    3    4    5
Zone                      
1       3.0  4.0  4.0  3.0
2       NaN  NaN  4.0  NaN
3       3.0  NaN  NaN  1.0
4       3.0  4.0  3.0  4.0

补充说明:如果希望无匹配数据的单元格不显示NaN,可以在pivot_table参数中加fill_value=0(或其他你需要的填充值)。本次透视逻辑不涉及Direction字段,不需要对该字段做额外处理。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.30 08:21:18