【问题标题】:PandasTypeError: unhashable type: 'slice'PandasTypeError:不可散列的类型:'sl​​ice'
【发布时间】:2019-05-23 00:48:48
【问题描述】:

我正在尝试运行以下代码,它在标题中显示错误。有人知道发生了什么吗?

import numpy as np
import matplotlib.pyplot as plt
import pandas as pd

dataset = pd.read_csv('Data.csv')

X = dataset.iloc[:, :-1].values
Y = dataset.iloc[:, 3].values

from sklearn.preprocessing import Imputer
imputer = Imputer(missing_values = 'NaN', strategy = 'mean', axis = 0)
imputer = imputer.fit(X[:, 1:3])
X[:, 1:3] = imputer.transform(X[:, 1:3])

X = pd.DataFrame(X)
Y = pd.DataFrame(Y)

from sklearn.preprocessing import LabelEncoder
labelencoder_X = LabelEncoder()
X[:, 0] = labelencoder_X.fit_transform(X[:, 0])

【问题讨论】:

  • 请编辑您的问题以包含完整的错误回溯
  • 你能展示一个你的数据框的例子吗?也许使用dataset.head()
  • ML、AI、spyder、DS 没什么可看的……只是 python 语法。
  • 标签是你的朋友,尽量明智地使用它们——这里肯定没有关于 artificial-intelligence 的内容(已编辑)

标签: python pandas machine-learning artificial-intelligence data-science


【解决方案1】:

X 是代码最后一行中的数据框,因此您不能使用基于数组的索引(就像使用 numpy array 一样),除非您使用 .loc.iloc。在这种情况下,您可以使用其中任一来访问第一列,因为位置 (0) 与列名称 (0) 相同:

X.loc[:, 0] = labelencoder_X.fit_transform(X.loc[:, 0])

熊猫documentation on indexing is quite good

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-08-15
    • 2016-05-13
    • 1970-01-01
    • 2015-07-05
    • 2017-07-11
    • 2016-03-16
    相关资源
    最近更新 更多