Python 对需要两个参数的函数使用rolling_apply
我正在尝试将rollapply与需要两个参数的公式一起使用。据我所知,计算kendall-tau相关性的唯一方法(除非您从头开始创建公式)包括标准校正:Python 对需要两个参数的函数使用rolling_apply,python,numpy,pandas,scipy,dataframe,Python,Numpy,Pandas,Scipy,Dataframe,我正在尝试将rollapply与需要两个参数的公式一起使用。据我所知,计算kendall-tau相关性的唯一方法(除非您从头开始创建公式)包括标准校正: >>> import scipy >>> x = [5.05, 6.75, 3.21, 2.66] >>> y = [1.65, 26.5, -5.93, 7.96] >>> z = [1.65, 2.64, 2.64, 6.95] >>> print s
>>> import scipy
>>> x = [5.05, 6.75, 3.21, 2.66]
>>> y = [1.65, 26.5, -5.93, 7.96]
>>> z = [1.65, 2.64, 2.64, 6.95]
>>> print scipy.stats.stats.kendalltau(x, y)[0]
0.333333333333
我也知道rollapply和接受两个参数的问题,如下所述:
A = pd.DataFrame([[1, 5, 1], [2, 4, 1], [3, 3, 1], [4, 2, 1], [5, 1, 1]],
columns=['A', 'B', 'C'], index = [1, 2, 3, 4, 5])
正在尝试创建一个函数来执行此操作
In [1]:function(A, 3) # A is df, 3 is the rolling window
Out[2]:
A B C AB AC BC
1 1 5 2 NaN NaN NaN
2 2 4 4 NaN NaN NaN
3 3 3 1 -0.99 -0.33 0.33
4 4 2 2 -0.99 -0.33 0.33
5 5 1 4 -0.99 0.99 -0.99
在一个非常初步的方法中,我接受了这样定义函数的想法:
def tau1(x):
y = np.array(A['A']) # keep one column fix and run it in the other two
tau, p_value = sp.stats.kendalltau(x, y)
return tau
A['AB'] = pd.rolling_apply(A['B'], 3, lambda x: tau1(x))
当然没用了。我得到:
ValueError: all keys need to be the same shape
我知道这不是一个小问题。非常感谢您的任何输入。,滚动应用
只将NumPy数组传递给函数。一种可能的解决方法是将np.arange(len(A))
作为rolling\u apply
的第一个参数,以便tau
函数接收您希望使用的行的索引。然后在tau
函数中
B = A[[col1, col2]].iloc[idx]
返回包含所需所有行的数据帧
屈服
A B C AB AC BC
1 1 5 2 NaN NaN NaN
2 2 4 4 NaN NaN NaN
3 3 3 1 -1 -0.333333 0.333333
4 4 2 2 -1 -0.333333 0.333333
5 5 1 4 -1 1.000000 -1.000000
太神了谢谢!。我应该记住的列数有限制吗?这些itertools功能非常棒,远远超过我的水平。。。询问任何其他智能问题。组合的数量会像
n**2
那样增长,因此tau
会按n**2*m
的顺序被调用,其中m=len(A)
。所以这可能需要一段时间,特别是如果你有很多专栏的话。真的很有趣;学习并不难,花时间也很值得。60K行x 4列~7分钟这对我帮助很大,谢谢!因为<代码> RoLungUpIpAp/<代码>将被弃用,您是否考虑更新您的解决方案为<代码> Pd?系列(NP.ARANGE(LeN(a)),index=A. index)。滚动(3)。应用(TAU)< /代码>?
A B C AB AC BC
1 1 5 2 NaN NaN NaN
2 2 4 4 NaN NaN NaN
3 3 3 1 -1 -0.333333 0.333333
4 4 2 2 -1 -0.333333 0.333333
5 5 1 4 -1 1.000000 -1.000000