I have a time-series A
holding multiple values in a series B
which is algebraically defined as:
b [t] = one * a [t] + b * b [t -1]
Where we can assume B [0] = 0
and a
and b
Are real numbers
Is there a way to calculate this type of recursive list? Or do I have no choice, as suggested in loop in Python?
As an example of input:
& gt; 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
As I have a comment As noted in, you can use. In this case (there is a one-dimensional numerical chaos assuming A
), you only need it:
B = lfilter ([a], [1.0, - b]], a)
here's a complete script:
import numpy scipy.signal import lfilter np.random.seed (123) a Calculate the recycling using NP.random.randn (10) a = 2.0 b = 3.0 # lfilter in the form of NP. # [A] and [1, -b] coefficient of fraction and filter transfer function # of the rot, resp. B = lfilter ([a], [1, -b], A) Print B # Compare with a simple loop B2 = np.empty (lane (a)) range (0, lane (b2)) in Kashmir For: K == 0 if: b2 [k] = one * a [k] rest: b2 [k] one = * a [k] + b * b2 [k-1] print b2 print "maximum difference : ", np.max (np.abs (B 2 - B))
the script:
[-2kl7l26l2le +00 -4k5l909273e +00 -lk299l32l2e + 0l + 0l -4kl9865530e -lk27ll6859e -3k78047705e +02 +02 +03 -lkl3899647e - 3k4l784725e -lk025l0099e +03 +04 +04 -3k0754763le] [-2kl7l26l2le +00 - 4k5l909273e +00 -lk299l32l2e + 0l + 0l -4kl9865530e -lk27ll6859e +02 -3k78047705e +02 -lkl3899647e + 03 -3k4l784725e -lk025l0099e +03 +04 +04 -3k0754763le] maximum difference: 0.0 < / Code>
one more Examples IPython, using a panda DataFrame instead of a numpy array:
If you have
[12]: df = pd.DataFrame (in [1, 7, 9, 5], column = ['A']) in [13]: DF out [13]: A1 1 7293 5
You want to create a column, B
, such as B [k] = A [k] + 2 * B [k-1]
( b [with] For & lt; == 0
0), you can type in [14]: df ['B'] = lfilter ([1], [1, -2], df ['A'] in
']. [15]: DF out [15]: AB 0 1 7 7792 9 27 3 5 59