【问题标题】:proc mean with weight python equivalentproc 与重量 python 等效的平均值
【发布时间】:2019-06-17 09:04:22
【问题描述】:

我正在将 SAS 转换为 python,并且遇到了与确切值不匹配的代码。 SAS 表示采用 associates 列和 pwgtp 列的加权平均值。但尝试在 python 值不匹配。

proc means data=hhhead1 nway noprint;
 weight pwgtp;
 var associates;
 output out=propassociates (drop=_:) mean=; run;

答案是 SAS 的 0.2871426408

我尝试了各种方法来获得权重平均值。 数据由 120 万行组成 无法分享数据抱歉

propassociates = hhhead1.groupby(by = ['PWGTP_y'])['associates'].mean().reset_index()

np.mean(propassociates['associates'])

答案是 0.26806426594942845

hhhead1['weight_sum'] = hhhead1['associates'] * hhhead1['PWGTP_x']
propassociates = hhhead1['weight_sum'].sum() / hhhead1['PWGTP_x'].sum()

答案是 0.08837267780237641

propassociates = hhhead1.groupby(by = ['PWGTP_y'])['associates'].mean().reset_index()

np.mean(propassociates['associates'])

答案是 0.26806426594942845

hhhead1['weight_sum'] = hhhead1['associates'] * hhhead1['PWGTP_x']
propassociates = hhhead1['weight_sum'].sum() / hhhead1['PWGTP_x'].sum()

答案是 0.08837267780237641

答案是 SAS 的 0.2871426408

答案是 0.26806426594942845

【问题讨论】:

  • 如果您无法共享数据,请考虑添加产生相同错误的替代数据
  • 使用 sashelp.class 数据集运行相同的代码,这很简单,可以共享,或者我认为类似于 mpg 的 sashelp.cars。

标签: python python-3.x numpy sas


【解决方案1】:
def wavg(group, avg_name, weight_name):
    d = group[avg_name]
    w = group[weight_name]
    try:
        return (d * w).sum() / w.sum()
    except ZeroDivisionError:
        return d.mean()
a=data1.groupby(['GroupByVar']).apply(wavg, "yourVar", "WeightVar")

这应该可以工作

【讨论】:

    猜你喜欢
    • 2016-06-10
    • 1970-01-01
    • 1970-01-01
    • 2022-11-03
    • 1970-01-01
    • 1970-01-01
    • 2016-01-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多