繁体   English   中英

熊猫:根据滚动窗口在数据框中创建新列

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM