簡體   English   中英

Pandas 中的遞歸定義

[英]Recursive definitions in Pandas

我有一個包含多個值的時間序列A 我需要獲得一個代數定義的系列B如下:

B[t] = a * A[t] + b * B[t-1]

我們可以假設B[0] = 0 ,並且ab是實數。

有沒有辦法在 Pandas 中進行這種遞歸計算? 或者我別無選擇,只能按照這個答案中的建議在 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

正如我在評論中指出的,您可以使用scipy.signal.lfilter 在這種情況下(假設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 中,使用 Pandas DataFrame 而不是 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 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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM