gpt4 book ai didi

python - 获取 Pandas 中多列的加权平均值和标准差

转载 作者:太空宇宙 更新时间:2023-11-03 14:14:15 29 4
gpt4 key购买 nike

我正在尝试在我的 pandas 数据帧上的加权平均值之上进行加权标准差。我有一个 pandas 数据框,例如:

import numpy as np
import pandas as pd
df = pd.DataFrame({"Date": pd.date_range(start='2018-01-01', end='2018-01-03 18:00:00', freq='6H'),
"Weight": np.random.uniform(3, 5, 12),
"V1": np.random.uniform(10, 15, 12),
"V2": np.random.uniform(10, 15, 12),
"V3": np.random.uniform(10, 15, 12)})

目前,要获取加权平均值,灵感来自 this post ,我正在执行以下操作:

def weighted_average_std(grp):
return grp._get_numeric_data().multiply(grp['Weight'], axis=0).sum()/grp['Weight'].sum()
df.index = df["Date"]
df_agg = df.groupby(pd.Grouper(freq='1D')).apply(weighted_average_std).reset_index()
df_agg

我从哪里得到以下信息:

    Date    V1  V2  V3  Weight
0 2018-01-01 11.421749 13.090178 11.639424 3.630196
1 2018-01-02 12.142917 11.605284 12.187473 4.056303
2 2018-01-03 12.034015 13.159132 11.658969 4.318753

我想修改weighted_average_std,以便除了加权平均值之外,它还返回每列的标准差。这个想法是以矢量化方式使用每个组的加权平均值。 加权标准差的新列名称可以类似于V1_WSDV2_WSDV3_WSD

PS1:This post回顾加权标准差理论。

PS2:df_agg 中的Weight 列没有意义。

最佳答案

你可以使用EOL's NumPy-based code计算加权平均值和标准差。要在 Pandas groupby/apply 操作中使用此功能,请使 weighted_average_std 返回一个 DataFrame:

import numpy as np
import pandas as pd


def weighted_average_std(grp):
"""
Based on http://stackoverflow.com/a/2415343/190597 (EOL)
"""
tmp = grp.select_dtypes(include=[np.number])
weights = tmp['Weight']
values = tmp.drop('Weight', axis=1)
average = np.ma.average(values, weights=weights, axis=0)
variance = np.dot(weights, (values - average) ** 2) / weights.sum()
std = np.sqrt(variance)
return pd.DataFrame({'mean':average, 'std':std}, index=values.columns)

np.random.seed(0)
df = pd.DataFrame({
"Date": pd.date_range(start='2018-01-01', end='2018-01-03 18:00:00', freq='6H'),
"Weight": np.random.uniform(3, 5, 12),
"V1": np.random.uniform(10, 15, 12),
"V2": np.random.uniform(10, 15, 12),
"V3": np.random.uniform(10, 15, 12)})

df.index = df["Date"]
df_agg = df.groupby(pd.Grouper(freq='1D')).apply(weighted_average_std).unstack(-1)
print(df_agg)

产量

                 mean                             std                    
V1 V2 V3 V1 V2 V3
Date
2018-01-01 12.105253 12.314079 13.566136 1.803014 1.725761 0.679279
2018-01-02 13.223172 12.534893 11.860456 1.709583 0.950338 1.153895
2018-01-03 13.782625 12.013557 12.105231 0.969099 1.189149 1.249064

关于python - 获取 Pandas 中多列的加权平均值和标准差,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48307663/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com