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

如何避免Pandas透视表数值聚合时出现NotImplementedError与TypeError

Pandas聚合时字符串列引发TypeError的解决方法

问题场景

多次执行Pandas数值聚合操作时,先触发NotImplementedError,随后抛出TypeError,核心错误提示为Could not convert Larry PagerLarry PagerLarry Pager to numeric,本质是Pandas尝试对字符串列执行数值聚合导致的。

给定数据集matrix_data(Pandas已导入为pan):

Account Number  Company      Contact Account Manager     Product  Licenses   
0         2123398   Google  Larry Pager    Edward Thorp   Analytics       150  
1         2123398   Google  Larry Pager    Edward Thorp  Prediction       150   
2         2123398   Google  Larry Pager    Edward Thorp    Tracking       300   
3         2192650     BOBO  Larry Pager    Edward Thorp   Analytics       150   
4          420496     IKEA    Elon Tusk    Edward Thorp   Analytics       300   

   Sale Price        Status  
0     2100000     Presented  
1      700000     Presented  
2      350000  Under Review  
3     2450000          Lost  
4     4550000           Won  

触发错误的代码:

# pivot_table方式
pan.pivot_table(matrix_data, index = "Company", aggfunc="mean");

# groupby方式
matrix_data.groupby(["Company"]).mean()

环境:Windows 10、Python 3.11、Pandas 2.0.1、VSCode Jupyter Notebook

解决方法

方法1:启用numeric_only=True参数

Pandas的pivot_table和groupby聚合方法都支持numeric_only参数,设置为True后会自动忽略非数值列,仅对数值型列执行聚合:

# pivot_table实现
pan.pivot_table(matrix_data, index="Company", aggfunc="mean", numeric_only=True)

# groupby实现
matrix_data.groupby(["Company"]).mean(numeric_only=True)

方法2:手动指定聚合列

明确指定需要聚合的数值列,避免Pandas遍历所有列:

matrix_data.groupby(["Company"])[["Licenses", "Sale Price"]].mean()

方法3:提前筛选数值列

先用select_dtypes筛选出所有数值型列,再结合分组操作:

# 筛选数值列
numeric_df = matrix_data.select_dtypes(include=['number'])
# 合并分组列后聚合
matrix_data[["Company"]].join(numeric_df).groupby(["Company"]).mean()

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.20 01:22:33