How to do the ADF Test for each column of my Dataframe in Python?

Viewed 914

I am looking for a way to do the ADF Test for multiple columns of a DataFrame. Any idea? Thanks.

This is my multi-column dataframe, how to calculate the test for each column separately

enter image description here

2 Answers

This is a function you can apply to columns of DataFrame:

from statsmodels.tsa.stattools import adfuller
import pandas as pd


def adfuller_test(series, signif=0.05):
"""
Perform Augmented Dickey-Fuller to test for Stationarity of the given series
and print report. Null Hypothesis: Data has unit root and is non-stationary.

series: time series in pd.Series format
signif: significance level for P-value to reject Null Hypothesis
"""
    x = adfuller(series, autolag='AIC')

    #using dictionary saves different data types (float, int, boolean)
    output = {'Test Statistic': x[0], 
              'P-value': x[1], 
              'Number of lags': x[2], 
              'Number of observations': x[3],
              f'Reject (signif. level {signif})': x[1] < signif }

    for key, val in x[4].items():
         output[f'Critical value {key}'] = val

return pd.Series(output)

You can follow like df_train.apply(lambda x: adfuller_test(x), axis=0) to get a summary.

Related