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

使用Pandas agg结合Numpy quantile为不同列传参计算分位数

问题:Pandas agg结合np.quantile实现列自定义分位数计算

问题重现

初始代码与DataFrame:

import pandas as pd
import numpy as np

df = pd.DataFrame({
      'A': [1, 2, 3, 4, 5],
      'B': [6, 7, 8, 9, 10]})

尝试的代码:

(df.
 agg({'A' : lambda x: np.quantile(a=x, q=0.25),
      'B' : lambda x: np.quantile(a=x, q=0.75)}))

得到的错误结果:

A     B
0  1.0   6.0
1  2.0   7.0
2  3.0   8.0
3  4.0   9.0
4  5.0  10.0

预期结果:

A    2.0
B    9.0
dtype: float64

问题核心:原lambda写法导致np.quantile被逐元素计算,而非对整列序列计算分位数。

解决方法

方法1:使用元组传递函数与参数(推荐)

直接在agg中用**(函数名, 参数)**的元组格式,Pandas会自动将整列序列作为第一个参数传入np.quantile:

df.agg({
    'A': (np.quantile, 0.25),
    'B': (np.quantile, 0.75)
})

运行后即可得到预期结果:

A    2.0
B    9.0
dtype: float64

方法2:修正lambda写法

如果坚持用lambda,需明确lambda接收的是整列Series对象,直接用该对象调用np.quantile:

df.agg({
    'A': lambda col: np.quantile(col, q=0.25),
    'B': lambda col: np.quantile(col, q=0.75)
})

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.25 11:40:05