gpt4 book ai didi

python - Pandas 的时间加权平均值

转载 作者:太空狗 更新时间:2023-10-29 21:06:06 25 4
gpt4 key购买 nike

在 Pandas 0.8 中计算 TimeSeries 的时间加权平均值的最有效方法是什么?例如,假设我想要 df.y - df.x 的时间加权平均值,如下所示:

import pandas
import numpy as np
times = np.datetime64('2012-05-31 14:00') + np.timedelta64(1, 'ms') * np.cumsum(10**3 * np.random.exponential(size=10**6))
x = np.random.normal(size=10**6)
y = np.random.normal(size=10**6)
df = pandas.DataFrame({'x': x, 'y': y}, index=times)

我觉得这个操作应该很容易做,但是我尝试过的所有操作都涉及到几个困惑而缓慢的类型转换。

最佳答案

您可以将 df.index 转换为整数并使用它来计算平均值。有一个返回 int64 值数组的快捷方式 asi8 属性:

np.average(df.y - df.x, weights=df.index.asi8)

关于python - Pandas 的时间加权平均值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10839701/

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