首页 > 解决方案 > Python pandas递归函数多项式形式

问题描述

我正在尝试在 python 中使用 Pandas 数据框创建递归函数。

我通读了一遍,似乎有几种不同的方法,要么是 for/if 循环,要么是 Dataframe.apply 方法;或 scipy.signal.lfilter。但是,lfilter对我不起作用,因为我的递归公式可以是多项式形式。

我想做的递归公式是:

x(t) = A * 出价 + B * x(t-1)^C + 出价Q

我查看了一些示例,其中一种可能性是以下形式。

import pandas as pd
import datetime as dt
import numpy as np
import scipy.stats as stats
import scipy.optimize as optimize
from scipy.signal import lfilter

@xw.func
@xw.ret(expand='table')
def py_Recursive(v, lamda_, AscendType):
    df = pd.DataFrame(v, columns=['Bid', 'Ask', 'BidQ', 'AskQ'])
    df = df.sort_index(ascending=AscendType)
    NewBid = lfilter([1], [1,-2], df['Bid'].astype=(float))
    df = df.join(NewBid)
    df = df.sort_index(ascending=True)
    return df

lamda_是一个衰减函数,可能会在未来使用,并且AscendTypeTRUE或者FALSE

我的输入数据集v如下

v =
763.1  763.3    89    65
762.5  762.7   861   687
772.1  772.3   226   761
770.6  770.8   927   333
777.8  778.0    59   162
786.5  786.7   125   431
784.7  784.9   915   595
776.8  777.0   393   843
777.7  777.9   711   935
771.6  771.8   871   956
770.0  770.2   727   300
768.7  768.9   565   923

标签: pythonpandasdataframerecursion

解决方案


所以我无法运行您的代码,但我认为您可以使用您提供的公式递归地创建列:

df = pd.DataFrame(v, columns=['Bid', 'Ask', 'BidQ', 'AskQ'])
# initialise your parameters, but they can be a function of something else
A, B, C = 10, 2, 0.5
x0 = 1
#create the column x filled with x0 first
df['x'] = x0
# now change each row depending on the previous one and other information
for i in range(1,len(df)):
    df.loc[i,'x'] = A*df.loc[i,'Bid'] + B*df.loc[i-1,'x']**C + df.loc[i,'BidQ']

推荐阅读