使用 statsmodels add_constant 时无法获取常量

问题描述 投票:0回答:1

我有以下使用 statsmodels 的 python 代码:

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)

输出是

[[   2010 4040100]]

我期望输出有一个

1
,因为我正在使用
add_constant
,但它不存在,我该如何修复它?我正在使用 statsmodels 版本 0.14.0

python statsmodels
1个回答
0
投票

add_constant()

默认行为是如果常量已经存在则跳过添加任何内容。
如果您将
has_constant
参数设置为
raise
,您将收到异常

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

将 has_constant 参数设置为

'add'
将添加您想要的新常量列。但是,我观察到默认情况下它会在新列前面添加,而文档指出默认行为应该是附加。这似乎是文档已过时的情况,因为我刚刚安装的库版本的前置参数的默认值为 True。

# 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]]
© www.soinside.com 2019 - 2024. All rights reserved.