Python 带熊猫的时间加权平均

Python 带熊猫的时间加权平均,python,time-series,pandas,Python,Time Series,Pandas,以0.8计算时间序列的时间加权平均值最有效的方法是什么?例如,假设我想要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

以0.8计算时间序列的时间加权平均值最有效的方法是什么?例如,假设我想要
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
转换为整数,并使用它来计算平均值。有一个快捷方式
asi8
属性,可返回int64值数组:

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

谢谢我想根据持续时间对值进行加权,所以我使用了
np.average((df.y-df.x)[:-1],weights=np.diff(df.index.asi8))