Pandas数列加权平均和标准差的求取

2024-05-08 23:18:24 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图在我的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的启发,我做了以下工作:

^{pr2}$

我得到以下信息:

    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,这样它除了返回weighted average之外,还返回每个列的标准偏差。其思想是以矢量化的方式使用每组的加权平均值。Weighted Standard Deviation的新列名可以是V1_WSDV2_WSD和{}。在

PS1:This post通过加权标准差理论。在

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


Tags: 数据importpandasdfdateasnprandom
1条回答
网友
1楼 · 发布于 2024-05-08 23:18:24

您可以使用EOL's NumPy-based code 计算加权平均数和标准差。要在Pandasgroupby/apply操作中使用它,请使weighted_average_std返回一个数据帧:

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)

收益率

^{pr2}$

相关问题 更多 >