3

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

  • Good question! You are not really transforming the existing data I believe. What is the output of `smt.AR(...)`? A number, vector, string? – gosuto Dec 09 '19 at 19:21
  • Specifically I am looking at x.params[0]. Since this is AR model of order 1, x.params[0] is a single value. It's coefficient value based on model output. – Abhishek Kulkarni Dec 09 '19 at 19:22

1 Answers1

3

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)
gosuto
  • 5,422
  • 6
  • 36
  • 57