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

如何从多个同列名DataFrame中提取指定列均值并存入列表

多DataFrame指定列均值批量计算方法

核心逻辑非常直接:

  • 先把所有需要处理的DataFrame统一归集到一个列表中
  • 遍历列表内的每个DataFrame,单独计算目标列的均值,将结果依次追加到最终结果列表即可

代码实现

import pandas as pd

# --------------- 测试数据构造 ---------------
DF1 = pd.DataFrame({
    'similarity': [0.2, 0.1, 0.46, 0.12, 0.6],
    'count': [2, 3, 4, 8, 10]
})
DF2 = pd.DataFrame({
    'similarity': [0.2, 0.1, 0.46, 0.12, 0.6],
    'count': [4, 3, 5, 6, 9]
})

# --------------- 核心计算逻辑 ---------------
# 1. 归集所有待处理的DataFrame
df_collection = [DF1, DF2]
# 2. 指定要计算的目标列名
target_column = 'similarity'
# 3. 列表推导式批量计算均值
mean_list = [df[target_column].mean() for df in df_collection]

运行上述代码后,mean_list的输出就是预期结果:

[0.296, 0.296]

注意:使用前请确认所有归集的DataFrame都包含你指定的目标列,否则会触发KeyError报错。如果后续有更多同结构的DataFrame需要计算,直接把新的DF追加到df_collection列表里即可,不需要修改计算逻辑。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.30 20:01:03