python - 如何防止python中的KeyErrors?
问题描述
在机器学习项目中使用 MinMaxScaler 时,我遇到了 KeyError 问题。这是我的相关代码:
df = pd.read_csv(io.BytesIO(uploaded['Root_Work_Sample.csv']))
print(df.shape)
print(df.columns)
display(df.head(5))
print(df.dtypes)
train_cols = ["feature1, feature2, feature3, feature4, feature5, feature6, feature7, feature8, feature9, feature10, feature11, feature12, feature13, feature14, y"]
df_train, df_test = train_test_split(df, train_size=1000, test_size=876, shuffle=False)
print("Train--Test size", len(df_train), len(df_test))
print(df_train)
print(df_test)
# scale the feature MinMax, build array
x = df_train.loc[:,train_cols].values #THE ERROR IS ON THIS LINE
min_max_scaler = MinMaxScaler()
x_train = min_max_scaler.fit_transform(x)
x_test = min_max_scaler.transform(df_test.loc[:,train_cols])
这是我得到的错误:
KeyError: "None of [Index(['feature1, feature2, feature3, feature4, feature5, feature6, feature7, feature8, feature9, feature10, feature11, feature12, feature13, feature14, y'], dtype='object')] are in the [columns]"
有没有关于如何解决这个问题的建议以及关于像我这样的新手如何避免这类错误的一般做法?
解决方案
df_train
不是数据框,它是 2D numpy 数组,因此您不能loc
在其上使用方法。我猜你train_test_split
以错误的方式使用函数。而且您指定train_cols
错误,您应该将每个功能用引号括起来,如下所示:
train_cols = ["feature", "feature2",....]
尝试这个:
X, y = df[train_cols], df["y"]
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=876, shuffle=False)
scaler = MinMaxScaler()
X_train_scaled = scaler.fit_transform(X_train)
X_test_scaled = scaler.transform(X_test)
推荐阅读
- hadoop - 如何在将 hive 作业提交到 dataproc 集群时执行 gcp 存储桶中的 hive 查询列表(在我的情况下为 gs:/hive/hive.sql")
- r - 顺序启动停止时间 R 之间的差异
- ios - 当我删除然后在tableview上添加一行时,它会添加删除的行
- c++ - 模拟流进行测试
- python-3.x - 向 3D 散点图添加标签不起作用
- node.js - API调用后Docusign文档空白
- reactjs - React 中的上下文总是空对象
- r - R `update.packages()` 删除一些包
- spring - 我可以在 Micronaut 中使用 spring data jpa 吗?
- mysql - 无法从 Cloud Foundry 应用程序连接到 mySQL 数据库