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

如何正确使用aggfunc=np.sum并抑制pandas pivot_table特定警告?

Pandas 2.x中pivot_table的FutureWarning解决方法

问题A:不想传字符串"sum",如何正确使用自定义可调用对象?

由于Pandas 2.x对内置聚合函数的可调用对象(如np.sum)会触发该警告,若你确实希望直接使用np.sum而非Pandas内置的DataFrameGroupBy.sum,可以将np.sum包装为自定义函数,让Pandas直接调用该可调用对象:

import numpy as np
import pandas as pd

def custom_sum(x):
    return np.sum(x)

df = pd.DataFrame([["a", 1], ["a", 2], ["b", 3]], columns=["col1", "col2"])
# 使用自定义包装后的函数
df.pivot_table(index="col1", values="col2", aggfunc=custom_sum)

这样既保留了直接调用np.sum的逻辑,又不会触发目标警告。

问题B:全局范围内抑制该特定警告

可以通过warnings.filterwarnings精准匹配警告的消息内容,仅屏蔽这一条FutureWarning,不影响其他有用的警告:

import warnings

# 过滤pandas模块发出的特定FutureWarning
warnings.filterwarnings(
    "ignore",
    message=r"The provided callable <function sum at .*> is currently using DataFrameGroupBy.sum. In a future version of pandas, the provided callable will be used directly. To keep current behavior pass the string \"sum\" instead.",
    category=FutureWarning,
    module="pandas"
)
  • message使用正则表达式匹配警告的具体文本(.*匹配内存地址的任意字符)
  • module="pandas"限定只过滤pandas模块发出的该警告,确保其他模块的FutureWarning正常显示

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.16 20:15:08