创建回归模型乘法报错:'str'与'int'不支持'<'运算
问题
在构建第三个回归模型时,需要在Part III g模型基础上添加两个由国家虚拟变量与ab_page变量相乘生成的交互变量。将相关列转为int类型后执行乘法操作时触发TypeError,报错信息为'<'' not supported between instances of 'str' and 'int'。
我的代码
import statsmodels.api as sm import pandas as pd # Convert columns to the correct data types df_merged['country_CA'] = df_merged['country_CA'].astype(int) df_merged['country_UK'] = df_merged['country_UK'].astype(int) df_merged['country_US'] = df_merged['country_US'].astype(int) df_merged['ab_page'] = df_merged['ab_page'].astype(int) # Create the interaction variables df_merged['US_inter'] = df_merged['country_US'] * df_merged['ab_page'] df_merged['UK_inter'] = df_merged['country_UK'] * df_merged['ab_page'] # Define the dependent variable (conversion) and independent variables y = df_merged['converted'] X = df_merged[['intercept', 'ab_page', 'country_US', 'country_UK', 'US_inter', 'UK_inter']] # Instantiate the logistic regression model logit_model = sm.Logit(y, X) # Fit the model logistic_regression_result = logit_model.fit() # Display the summary of the logistic regression model print(logistic_regression_result.summary())
错误信息
TypeError Traceback (most recent call last) <ipython-input-163-6251061c8b0e> in <module>() 10 11 # Create the interaction variables ---> 12 df_merged['US_inter'] = df_merged['country_US'] * df_merged['ab_page'] 13 df_merged['UK_inter'] = df_merged['country_UK'] * df_merged['ab_page'] 14 /opt/conda/lib/python3.6/site-packages/pandas/core/ops.py in f(self, other, axis, level, fill_value) 1552 return _combine_series_frame(self, other, na_op, 1553 fill_value=fill_value, axis=axis, -> 1554 level=level, try_cast=True) 1555 else: 1556 if fill_value is not None: /opt/conda/lib/python3.6/site-packages/pandas/core/ops.py in _combine_series_frame(self, other, func, fill_value, axis, level, try_cast) 1437 # default axis is columns 1438 return self._combine_match_columns(other, func, level=level, -> 1439 try_cast=try_cast) 1440 1441 /opt/conda/lib/python3.6/site-packages/pandas/core/frame.py in _combine_match_columns(self, other, func, level, try_cast) 4767 def _combine_match_columns(self, other, func, level=None, try_cast=True): 4768 left, right = self.align(other, join='outer', axis=1, level=level, -> 4769 copy=False) 4770 4771 new_data = left._data.eval(func=func, other=right, /opt/conda/lib/python3.6/site-packages/pandas/core/frame.py in align(self, other, join, axis, level, copy, fill_value, method, limit, fill_axis, broadcast_axis) 3548 method=method, limit=limit, 3549 fill_axis=fill_axis, -> 3550 broadcast_axis=broadcast_axis) 3551 3552 @Appender(_shared_docs['reindex'] % _shared_doc_kwargs) /opt/conda/lib/python3.6/site-packages/pandas/core/generic.py in align(self, other, join, axis, level, copy, fill_value, method, limit, fill_axis, broadcast_axis) 7368 copy=copy, fill_value=fill_value, 7369 method=method, limit=limit, -> 7370 fill_axis=fill_axis) 7371 else: # pragma: no cover 7372 raise TypeError('unsupported type: %s' % type(other)) /opt/conda/lib/python3.6/site-packages/pandas/core/generic.py in _align_series(self, other, join, axis, level, copy, fill_value, method, limit, fill_axis) 7462 join_index, lidx, ridx = self.columns.join( 7463 other.index, how=join, level=level, -> 7464 return_indexers=True) 7465 7466 if lidx is not None: /opt/conda/lib/python3.6/site-packages/pandas/core/indexes/base.py in join(self, other, how, level, return_indexers, sort) 3770 this = self.astype('O') 3771 other = other.astype('O') -> 3772 return this.join(other, how=how, return_indexers=return_indexers) 3773 3774 _validate_join_method(how) /opt/conda/lib/python3.6/site-packages/pandas/core/indexes/base.py in join(self, other, how, level, return_indexers, sort) 3780 if self.is_monotonic and other.is_monotonic: 3781 return self._join_monotonic(other, how=how, -> 3782 return_indexers=return_indexers) 3783 else: 3784 return self._join_non_unique(other, how=how, /opt/conda/lib/python3.6/site-packages/pandas/core/indexes/base.py in _join_monotonic(self, other, how, return_indexers) 4046 join_index, lidx, ridx = self._inner_indexer(sv, ov) 4047 elif how == 'outer': -> 4048 join_index, lidx, ridx = self._outer_indexer(sv, ov) 4049 join_index = self._wrap_joined_index(join_index, other) 4050 pandas/_libs/join_helper.pxi in pandas._libs.join.outer_join_indexer_object() TypeError: '<' not supported between instances of 'str' and 'int'
数据列类型详情
user_id int64 timestamp datetime64[ns] group object landing_page object converted int64 intercept int64 ab_page int64 country object country_CA int64 country_UK int64 country_US int64 country_CA int64 country_UK int64 country_US int64 country_CA int64 country_UK int64 country_US int64 country_CA int64 country_UK int64 country_US int64 country_CA int64 country_UK int64 country_US int64 country_CA int64 country_UK int64 country_US int64 dtype: object
解决方案
从数据列类型详情可以看到,country_CA、country_UK、country_US列重复出现了多次,这会导致Pandas在执行列操作时出现索引对齐异常——重复列名会干扰内部索引处理逻辑,进而触发字符串与整数的比较错误。
解决步骤:
- 删除重复列:保留一组国家虚拟变量列即可,删除其余重复项
- 确认列类型:确保保留的列确实为int类型
- 生成交互变量:基于去重后的列执行乘法操作
修改后的代码:
import statsmodels.api as sm import pandas as pd # 删除重复的国家虚拟变量列,仅保留第一组 df_merged = df_merged.loc[:, ~df_merged.columns.duplicated()] # 确认并转换列类型(去重后列类型已正确,此步骤可选) df_merged['country_CA'] = df_merged['country_CA'].astype(int) df_merged['country_UK'] = df_merged['country_UK'].astype(int) df_merged['country_US'] = df_merged['country_US'].astype(int) df_merged['ab_page'] = df_merged['ab_page'].astype(int) # 生成交互变量 df_merged['US_inter'] = df_merged['country_US'] * df_merged['ab_page'] df_merged['UK_inter'] = df_merged['country_UK'] * df_merged['ab_page'] # 定义变量并构建模型 y = df_merged['converted'] X = df_merged[['intercept', 'ab_page', 'country_US', 'country_UK', 'US_inter', 'UK_inter']] logit_model = sm.Logit(y, X) logistic_regression_result = logit_model.fit() print(logistic_regression_result.summary())
另外,也可以使用statsmodels内置方法生成交互项,避免手动乘法的潜在问题:
# 替代手动生成交互项的方式 X = sm.add_constant(df_merged[['ab_page', 'country_US', 'country_UK']]) X['US_inter'] = X['country_US'] * X['ab_page'] X['UK_inter'] = X['country_UK'] * X['ab_page']
内容的提问来源于stack exchange,提问作者Josh VanDyke
相关产品推荐
相关产品推荐

