[英]Pandas: create a new column in a dataframe that is a function of a rolling window
我有一個數據框,可以使用pandas.stats.moments.rolling_mean(ExistingColumn, 10, min_periods=10)
計算滾動10個周期平均值的新列。 如果少於10個周期可用,我會得到NaN。 對於滾動中位數,我也可以這樣做。 完善。
我現在想計算N個周期的其他滾動函數,但是我一生都無法弄清楚如何對Pandas使用用戶定義的函數。 特別是,我想計算滾動的十點霍奇斯雷曼均值,其定義如下:
def hodgesLehmanMean(x):
return 0.5 * statistics.median(x[i] + x[j] for i in range(len(x)) for j in range(i+1,len(x)))
如果傳遞給少於10個周期,如何將其轉換為可應用於Pandas數據框並返回NaN的滾動函數? 我是Pandas的新手,所以我特別想舉一個例子做一個簡單的解釋。
您可以使用pandas.rolling_apply
:
import numpy as np
def hodgesLehmanMean(x):
return 0.5 * np.median([x[i] + x[j]
for i in range(len(x))
for j in range(i+1,len(x))])
df = pd.DataFrame({'foo': np.arange(20, dtype='float')})
df['bar'] = pd.rolling_apply(df['foo'], 10, hodgesLehmanMean)
print(df)
產量
foo bar
0 0 NaN
1 1 NaN
2 2 NaN
3 3 NaN
4 4 NaN
5 5 NaN
6 6 NaN
7 7 NaN
8 8 NaN
9 9 4.5
10 10 5.5
11 11 6.5
12 12 7.5
13 13 8.5
14 14 9.5
15 15 10.5
16 16 11.5
17 17 12.5
18 18 13.5
19 19 14.5
hodgesLehmanMean
的更快版本將是:
def hodgesLehmanMean_alt(x):
m = np.add.outer(x,x)
ind = np.tril_indices(len(x), -1)
return 0.5 * np.median(m[ind])
這是一個健全性檢查,顯示針對1000個長度為100的隨機數組, hodgesLehmanMean_alt
返回的值與hodgesLehmanMean
相同:
In [68]: m = np.random.random((1000, 100))
In [69]: all(hodgesLehmanMean(x) == hodgesLehmanMean_alt(x) for x in m)
Out[69]: True
這是一個顯示hodgesLehmanMean_alt
快約8倍的基准:
In [80]: x = np.random.random(5000)
In [81]: %timeit hodgesLehmanMean(x)
1 loops, best of 3: 3.99 s per loop
In [82]: %timeit hodgesLehmanMean_alt(x)
1 loops, best of 3: 463 ms per loop
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.