【发布时间】:2022-07-25 17:45:57
【问题描述】:
我创建了一个名为 train 的 pandas 数据框,如下所示:
import pandas as pd
import numpy as np
import statsmodels.api as sm
import statsmodels.formula.api as smf
ds = {
'matchKey' : [621062, 622750, 623508, 626451, 626611, 626796, 627114, 630055, 630225],
'og_max_last_dpd' : [1, 1, -99999, 1, 1, 1, 1, 1, 1],
'og_min_last_dpd' : [1, 1, -99999, 1, 1, 1, 1, 1, 1],
'og_max_max_dpd' : [0, 0, -99999, 1, 0, 5, 0, 4, 0]
}
train = pd.DataFrame(data=ds)
数据框如下所示:
print(train)
matchKey og_max_last_dpd og_min_last_dpd og_max_max_dpd
0 621062 1 1 0
1 622750 1 1 0
2 623508 -99999 -99999 -99999
3 626451 1 1 1
4 626611 1 1 0
5 626796 1 1 5
6 627114 1 1 0
7 630055 1 1 4
8 630225 1 1 0
我需要将值 -99999 替换为使用二项式 glm 函数估计的一些值。所以,我做了以下事情:
featuresToReplaceSV = ['og_max_last_dpd','og_min_last_dpd','og_max_max_dpd']
for n in range(len(featuresToReplaceSV)):
train['Flag1']=np.where(train[featuresToReplaceSV[n]]==-99999,0,1)
train['Flag0']=np.where(train[featuresToReplaceSV[n]]!=-99999,0,1)
# Estimate the Mini-Model
miniModel = smf.glm(formula='Y~Flag0 + Flag1 + Flag1:'+featuresToReplaceSV[n]+' - 1', data=train, family=sm.families.Binomial()).fit()
# Parameters
beta0_hat=miniModel.params[0]
beta1_hat=miniModel.params[1]
beta2_hat=miniModel.params[2]
# Mapping
Mapping=(beta0_hat-beta1_hat)/beta2_hat
print(Mapping)
print("Replace SV for pred char: ",featuresToReplaceSV[n])
train[featuresToReplaceSV[n]] = train[featuresToReplaceSV[n]].replace(-99999, Mapping)
但我收到以下错误:
PatsyError: Error evaluating factor: NameError: name 'Y' is not defined
Y~Flag0 + Flag1 + Flag1:og_max_last_dpd - 1
^
我不明白为什么会收到此错误。
我在这个链接中遇到过类似的问题:NameError: name 'y' is not defined
但我仍然无法弄清楚为什么会出现该错误。
谁能帮帮我?
【问题讨论】:
标签: python pandas glm patsy smf