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

如何计算pandas DataFrame指定列特定行的平均值并添加为新列

实现方法

你可以通过pandas的位置索引iloc先定位到指定行的norm列,再计算平均值即可,操作分两步:

  1. 计算目标行范围的平均值
    注意pandas默认的位置索引从0开始计数,且iloc的切片规则为左闭右开:
# 取自然顺序第450~453行(对应位置索引449~452)的norm列计算平均值
target_avg = df['norm'].iloc[449:453].mean()

# 如果你是要取索引值恰好为450、451、452、453的行,改用loc即可(loc切片左闭右闭)
# target_avg = df['norm'].loc[450:453].mean()
  1. 将平均值作为新列添加到原DataFrame
    因为计算得到的target_avg是标量值,赋值后pandas会自动为所有行填充该数值:
df['average'] = target_avg

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.04 14:57:04