我正在为数据科学奥林匹克竞赛而学习,但遇到了一个小问题。我完成的所有操作都是使用bin连续将2-8范围内的值转换为好或坏,然后我使用标签编码器将其设置为1或0
运行此代码时:
import pandas as pd
import numpy as np
from sklearn.ensemble import RandomForestClassifier
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler, LabelEncoder
#load our data file
data = pd.read_csv("data.csv", delimiter=";")
#classify wines as good or bad
bins = (1,5,8)
group_names = ['bad', "good"]
data["quality"] = pd.cut(data["quality"], bins=bins, labels=group_names)
print(data["quality"].unique())
#list the labels as good or bad to 1 or 0
label_quality = LabelEncoder()
data["quality"] = label_quality.fit_transform(data["quality"])
#create our feature ad result sets
X = data.drop(data["quality"], axis=1)
y = data["quality"]
#create our training sets
X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=10)
print(data.head(100))
我遇到了错误:
Traceback (most recent call last):
File "main.py", line 21, in <module> X = data.drop(data["quality"], axis=1)
File "/home/runner/.local/share/virtualenvs/python3/lib/python3.8/site-packages/pandas/core/frame.py", line 3990, in drop return super().drop(
File "/home/runner/.local/share/virtualenvs/python3/lib/python3.8/site-packages/pandas/core/generic.py", line 3936, in drop obj = obj._drop_axis(labels, axis, level=level, errors=errors)
File "/home/runner/.local/share/virtualenvs/python3/lib/python3.8/site-packages/pandas/core/generic.py", line 3970, in _drop_axis new_axis = axis.drop(labels, errors=errors)
File "/home/runner/.local/share/virtualenvs/python3/lib/python3.8/site-packages/pandas/core/indexes/base.py", line 5018, in drop raise KeyError(f"{labels[mask]} not found in axis")
KeyError: '[0 0 0 ... 1 0 1] not found in axis'
它说在轴中找不到我的行值,但是我已经指定了一个轴,所以它不应该切吗?
答案 0 :(得分:2)
实际上您的python代码有误,drop函数将列名称作为列表,而不是列本身,只需尝试下面的代码就可以了
#create our feature ad result sets
y = data["quality"]
X = data.drop(["quality"], axis=1)
还有另一件事,在删除之前,您必须在y中复制该列,否则将由于列'quality'被删除而产生错误