use*_*303 8 python time-series pandas
计算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)
Run Code Online (Sandbox Code Playgroud)
我觉得这个操作应该很容易做到,但我尝试过的所有内容都涉及到几个混乱和缓慢的类型转换.
您可以转换df.index为整数并使用它来计算平均值.有一个快捷方式asi8属性,它返回一个int64值的数组:
np.average(df.y - df.x, weights=df.index.asi8)
Run Code Online (Sandbox Code Playgroud)