Python"TypeError:无法散列的类型:'slice'"用于编码分类数据 [英] Python "TypeError: unhashable type: 'slice'" for encoding categorical data
本文介绍了Python"TypeError:无法散列的类型:'slice'"用于编码分类数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我得到
TypeError:不可散列的类型:'slice'
TypeError: unhashable type: 'slice'
在执行以下代码以在Python中对分类数据进行编码时.谁能帮忙吗?
when executing the below code for encoding categorical data in Python. Can anyone please help?
# Importing the libraries
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
# Importing the dataset
dataset = pd.read_csv('50_Startups.csv')
y=dataset.iloc[:, 4]
X=dataset.iloc[:, 0:4]
# Encoding categorical data
from sklearn.preprocessing import LabelEncoder, OneHotEncoder
labelencoder_X = LabelEncoder()
X[:, 3] = labelencoder_X.fit_transform(X[:, 3])
推荐答案
X
是一个数据框,无法通过切片术语(如X[:, 3]
)进行访问.您必须通过 iloc
或 X.values
.但是,您构造X
的方式使其成为副本...如此.我会用values
X
is a dataframe and can't be accessed via slice terminology like X[:, 3]
. You must access via iloc
or X.values
. However, the way you constructed X
made it a copy... so. I'd use values
# Importing the libraries
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
# Importing the dataset
# dataset = pd.read_csv('50_Startups.csv')
dataset = pd.DataFrame(np.random.rand(10, 10))
y=dataset.iloc[:, 4]
X=dataset.iloc[:, 0:4]
# Encoding categorical data
from sklearn.preprocessing import LabelEncoder, OneHotEncoder
labelencoder_X = LabelEncoder()
# I changed this line
X.values[:, 3] = labelencoder_X.fit_transform(X.values[:, 3])
这篇关于Python"TypeError:无法散列的类型:'slice'"用于编码分类数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文