Cannot get a constant when using statsmodels add_constant

28 Views Asked by At

I have the following python code using statsmodels:

import numpy as np
import statsmodels.api as sm

# Assuming future_time_points is an array like this
future_time_points = np.array([2010])

# Stacking future_time_points and its square
stacked_array = np.column_stack((future_time_points, future_time_points ** 2))

# Adding a constant column to the stacked array
array_with_constant = sm.add_constant(stacked_array)

print(array_with_constant)

The output is [[ 2010 4040100]]

I was expecting the output to have a 1 because I am using add_constant, however it is not there, how can I fix it? I am using statsmodels version 0.14.0

1

There are 1 best solutions below

1
nigh_anxiety On

The default behavior of add_constant() is to skip adding anything if a constant is already present.
If you set the has_constant parameter to raise, you will get the Exception

ValueError: Column(s) 0,1 are constant.

Setting the has_constant parameter to 'add' will add the new constant column you want. However, I observed that by default it prepended the new column, while the documentation states the default behavior should be to append. This appears to be a case of the documentation being out of date as the version of the library I just installed has a default value of True for the prepend parameter.

# Adding a constant column to the stacked array
array_with_constant = sm.add_constant(stacked_array, has_constant="add")

# Output ->  [[1.0000e+00 2.0100e+03 4.0401e+06]]

---------------------

# Adding a constant column to the stacked array
# With explicit prepend = False
array_with_constant = sm.add_constant(stacked_array, False, has_constant="add")

# Output -> [[2.0100e+03 4.0401e+06 1.0000e+00]]