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

如何用Python Pandas的pivot_table实现类似Excel的匹配计数透视表?

解决Pandas pivot_table实现Excel透视表分组统计问题

正确实现代码

要实现按「Instrument ID」分组、以「Match」为列字段统计对应匹配值数量的效果,推荐以下两种写法:

方法1:使用aggfunc='size'(最直接)

import pandas as pd

# 生成目标透视表
pivot_result = results.pivot_table(
    index='Instrument ID',
    columns='Match',
    aggfunc='size',
    fill_value=0
)
print(pivot_result)
  • aggfunc='size':直接统计Instrument ID与Match组合的分组行数,完全匹配你需要的「对应匹配值数量」需求
  • fill_value=0:自动填充不存在的分组组合为0,避免结果中出现NaN值

方法2:使用aggfunc='count'

如果需要指定values参数,可选择任意无空值的列(比如Instrument ID本身):

pivot_result = results.pivot_table(
    index='Instrument ID',
    columns='Match',
    values='Instrument ID',
    aggfunc='count',
    fill_value=0
)

原代码报错原因

你之前的代码报错核心问题有两个:

  1. np.count_nonzero不适用:该函数仅针对数值类型统计非零值,若Match列是字符串或其他非数值类型,会直接触发错误
  2. values='Match'逻辑冲突:当columns和values同时指定为Match时,pivot_table会尝试对Match列自身的非零值计数,逻辑上完全不符合你的分组统计需求

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.19 17:00:09