使用scikit-learn StandardScaler拟合DataFrame时遇类型错误求助
问题重现
执行scaler.fit(data[map_keys])时触发如下错误:
TypeError: Feature names are only supported if all input features have string names, but your input has ['str', 'str_'] as feature name / column name types. If you want feature names to be stored and validated, you must convert them all to strings, by using X.columns = X.columns.astype(str) for example. Otherwise you can remove feature / column names from your input data, or convert them all to a non-string data type.
已将map_keys列表中的元素全部转为原生str类型,但错误依然存在,使用scikit-learn版本为1.2.1。
根本原因
虽然你把索引用的map_keys转成了str,但原DataFrame的列名本身还是np.str_类型。当你用data[map_keys]提取子数据框时,返回的列名依然保留原有的np.str_类型,导致sklearn检测到混合类型的特征名,触发错误。
解决方案
直接将原DataFrame的列名转换为原生Python字符串类型:
# 可选:先确认列名类型 print([type(col) for col in data.columns]) # 转换所有列名为原生str data.columns = data.columns.astype(str) # 再执行拟合操作 scaler.fit(data[map_keys])
补充说明
scikit-learn 1.2及以上版本对特征名的类型一致性做了严格校验,要求所有特征名必须是同一种类型(要么全是原生str,要么全是非字符串类型)。仅转换索引列表无法改变子数据框的列名类型,必须直接修改原DataFrame的列名类型才能解决问题。
内容的提问来源于stack exchange,提问作者Lev_Descartski

