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

如何用Pandas获取各列nsmallest值的平均值以拟合下界

按列取最小n个值的平均值并生成目标Series

直接用apply()遍历DataFrame的每一列,对每一列单独调用nsmallest(n)取最小的n个值,再求平均值即可,代码示例如下:

import pandas as pd

# 假设你的目标DataFrame为df,n是需要取的最小数值的数量
# 对每列计算最小n个值的平均值
lower_bound_series = df.apply(lambda col: col.nsmallest(n).mean())
# 可选:给Series命名为'y',索引对应x值(原列名)
lower_bound_series = lower_bound_series.rename('y')

示例验证

构造测试数据:

test_data = {
    0: [5, 2, 8, 1],  # x=0对应的y值
    1: [3, 6, 0, 4],  # x=1对应的y值
    2: [9, 1, 7, 3]   # x=2对应的y值
}
df = pd.DataFrame(test_data)
n = 2

# 执行计算
result = df.apply(lambda col: col.nsmallest(n).mean()).rename('y')
print(result)

输出结果:

0    1.5
1    1.5
2    2.0
Name: y, dtype: float64

这个Series的索引就是x值(原DataFrame的列名),值为对应x下最小n个y值的平均值,完全符合需求。

注:df.nsmallest(n)是对整个DataFrame筛选行维度的最小n行,而非按列处理,所以无法直接满足需求,而apply()可以实现逐列的自定义操作。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.25 08:07:09