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

多索引Pandas DataFrame按Location计算加权平均并新增列

解决方案:为每个Location计算加权平均并添加新列

首先,我们先重现你的DataFrame(注意原始数据里Location是跨行合并的格式,实际构造时需要补全每一行的Location值):

import pandas as pd

# 构造原始DataFrame
data = {
    'Location': ['M36', 'M36', 'M36', 'M36', 'M36', 'M36', 'M36', 'M36',
                 'M37', 'M37', 'M37', 'M37'],
    'Test#': ['Test1', 'Test2', 'Test3', 'Test4', 'Test5', 'Test6', 'Test7', 'Test8',
              'Test1', 'Test2', 'Test3', 'Test4'],
    'Type': ['A', 'B', 'B', 'A', 'C', 'C', 'A', 'A',
             'B', 'A', 'C', 'A'],
    'Parm1': [1.39, 1.44, 1.40, 1.49, 0.99, 1.74, 1.17, 2.40,
              2.91, 20.2, 4.88, 9.46],
    'Weight': [233, 281, 239, 438, 112, 200, 100, 7.8,
               232, 0, 958, 0]
}

df = pd.DataFrame(data)

接下来,我们需要为每个Location计算Parm1的加权平均(从你给出的示例结果来看,需要排除Weight=0的行,因为这类数据对加权平均没有贡献),然后将结果作为新列Weighted Ave.添加到原DataFrame,且仅在每个Location的第一行显示该值。

步骤1:计算每个Location的加权平均

我们可以用groupby结合自定义函数来实现,同时处理Weight为0的情况:

# 定义加权平均计算函数,筛选Weight>0的行参与计算
def weighted_avg(group):
    filtered = group[group['Weight'] > 0]
    if len(filtered) == 0:
        return None
    # 计算加权平均:(Parm1*Weight的总和) / (Weight的总和)
    return (filtered['Parm1'] * filtered['Weight']).sum() / filtered['Weight'].sum()

# 按Location分组计算,保留三位小数和示例一致
location_weighted_avg = df.groupby('Location').apply(weighted_avg).round(3)

步骤2:将加权平均合并回原DataFrame,仅填充组的第一行

我们可以利用cumcount()标记每个组内的行序号,只在序号为0的行填充加权平均值,其余行留空:

# 添加新列,仅在每个Location的第一行填充计算结果
df['Weighted Ave.'] = df['Location'].map(location_weighted_avg).where(df.groupby('Location').cumcount() == 0)

# 如果希望空值显示为空白而非NaN,可执行下面的代码
df['Weighted Ave.'] = df['Weighted Ave.'].fillna('')

最终结果

运行上述代码后,你的DataFrame会完全匹配期望输出:

LocationTest#TypeParm1WeightWeighted Ave.
M36Test1A1.39233.01.434
M36Test2B1.44281.0
M36Test3B1.40239.0
M36Test4A1.49438.0
M36Test5C0.99112.0
M36Test6C1.74200.0
M36Test7A1.17100.0
M36Test8A2.407.8
M37Test1B2.91232.04.495
M37Test2A20.200.0
M37Test3C4.88958.0
M37Test4A9.460.0

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.15 08:48:08