Python 熊猫中的递归定义
我有一个包含多个值的时间序列Python 熊猫中的递归定义,python,numpy,pandas,Python,Numpy,Pandas,我有一个包含多个值的时间序列a。我需要获得一个序列B,它的代数定义如下: B[t] = a * A[t] + b * B[t-1] 其中我们可以假设B[0]=0,a和B是实数 有没有办法在熊猫中进行这种类型的递归计算?还是我别无选择,只能按照中的建议在Python中循环 作为输入示例: > A = pd.Series(np.random.randn(10,)) 0 -0.310354 1 -0.739515 2 -0.065390 3 0.214966 4 -0.
a
。我需要获得一个序列B
,它的代数定义如下:
B[t] = a * A[t] + b * B[t-1]
其中我们可以假设B[0]=0
,a
和B
是实数
有没有办法在熊猫中进行这种类型的递归计算?还是我别无选择,只能按照中的建议在Python中循环
作为输入示例:
> A = pd.Series(np.random.randn(10,))
0 -0.310354
1 -0.739515
2 -0.065390
3 0.214966
4 -0.605490
5 1.293448
6 -3.068725
7 -0.208818
8 0.930881
9 1.669210
正如我在评论中指出的,您可以使用。在这种情况下(假设
A
是一个一维numpy数组),您只需要:
B = lfilter([a], [1.0, -b], A)
以下是完整的脚本:
import numpy as np
from scipy.signal import lfilter
np.random.seed(123)
A = np.random.randn(10)
a = 2.0
b = 3.0
# Compute the recursion using lfilter.
# [a] and [1, -b] are the coefficients of the numerator and
# denominator, resp., of the filter's transfer function.
B = lfilter([a], [1, -b], A)
print B
# Compare to a simple loop.
B2 = np.empty(len(A))
for k in range(0, len(B2)):
if k == 0:
B2[k] = a*A[k]
else:
B2[k] = a*A[k] + b*B2[k-1]
print B2
print "max difference:", np.max(np.abs(B2 - B))
脚本的输出为:
[ -2.17126121e+00 -4.51909273e+00 -1.29913212e+01 -4.19865530e+01
-1.27116859e+02 -3.78047705e+02 -1.13899647e+03 -3.41784725e+03
-1.02510099e+04 -3.07547631e+04]
[ -2.17126121e+00 -4.51909273e+00 -1.29913212e+01 -4.19865530e+01
-1.27116859e+02 -3.78047705e+02 -1.13899647e+03 -3.41784725e+03
-1.02510099e+04 -3.07547631e+04]
max difference: 0.0
另一个例子是,在IPython中,使用熊猫数据帧而不是numpy数组: 如果你有
In [12]: df = pd.DataFrame([1, 7, 9, 5], columns=['A'])
In [13]: df
Out[13]:
A
0 1
1 7
2 9
3 5
您希望创建一个新列,B
,这样B[k]=a[k]+2*B[k-1]
(对于k<0,使用B[k]==0
)就可以编写
In [14]: df['B'] = lfilter([1], [1, -2], df['A'].astype(float))
In [15]: df
Out[15]:
A B
0 1 1
1 7 9
2 9 27
3 5 59
这里有一个公开的问题,可以对其进行Cythonization:,但有些链接也是它们的链接,您可以使用
scipy.signal.lfilter
。请参阅,以获取示例。精彩的答案。谢谢你,沃伦。我参加了信号与系统课程(奥本海姆的书),这感觉很对。我会仔细研究这个答案,因为它看起来是解决问题的正确方法。我认为这种方法只能处理线性递归,对吗?是的,只能处理线性递归。(lfilter
中的l
表示线性
)