Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Applying statsmodels Autoregression function on all pandas dataframe columns

I am trying to fit Autoregressive model on some data which is in pandas dataframe.

My current code:-

import pandas as pd
import statsmodels.tsa.api as smt
store=[]

df = pd.DataFrame({'A':[0.345, 0.985, 0.912, 0.645, 0.885, 0.121],
                       'B':[0.475, 0.502, 0.312, 0.231, 0.450, 0.234],
                       'C':[0.098, 0.534, 0.125, 0.984, 0.236, 0.734],
                       'D':[0.345, 0.467, 0.935, 0.074, 0.623, 0.469]})

for i in range(len(df.columns)):
    x=smt.AR(df.iloc[:,i]).fit(maxlag=1, ic='aic', trend='nc')
    store.append(x)

I was wondering if I could use apply or applymap or lambda function instead of for loop

like image 445
Abhishek Kulkarni Avatar asked Feb 25 '26 03:02

Abhishek Kulkarni


1 Answers

I can't test it because I dont have these packages but judging from the example given in .apply()'s docs you should just be able to do this:

def fit_it(vector):
   return smt.AR(vector).fit(maxlag=1, ic='aic', trend='nc').params[0]

results = df.apply(fit_it, axis=0, reduce=True)
like image 193
jorijnsmit Avatar answered Feb 27 '26 16:02

jorijnsmit



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!