2

我正在尝试制作一个简单的散点图并获得KeyError.

我试图查看是否是包含四个类的功能“组”的问题,但不是所以我不确定这里有什么问题。


from sklearn.datasets import load_iris

iris = load_iris()
iris_nparray = iris.data
iris_dataframe = pd.DataFrame(iris.data, columns=iris.feature_names)
iris_dataframe["group"] = pd.Series([iris.target_names[k] for k in iris.target], dtype = "category")

colors_palete = {0:"red", 1:"yellow", 2:"blue"}
colors = [colors_palete[c] for c in iris_dataframe["group"]]
simple_scatterplot = iris_dataframe.plot(kind = "scatter",x="petal length (cm)", y="petal width (cm)", c =colors)

预期的:

A nice colorful scatterplot

实际结果:

KeyError                                  Traceback (most recent call last)
<ipython-input-128-818f07044064> in <module>
      1 colors_palete = {0:"red", 1:"yellow", 2:"blue"}
----> 2 colors = [colors_palete[c] for c in iris_dataframe["group"]]
      3 simple_scatterplot = iris_dataframe.plot(kind = "scatter",x="petal length (cm)", y="petal width (cm)", c =colors)

<ipython-input-128-818f07044064> in <listcomp>(.0)
      1 colors_palete = {0:"red", 1:"yellow", 2:"blue"}
----> 2 colors = [colors_palete[c] for c in iris_dataframe["group"]]
      3 simple_scatterplot = iris_dataframe.plot(kind = "scatter",x="petal length (cm)", y="petal width (cm)", c =colors)

KeyError: 'setosa'```
4

1 回答 1

3

答案很简单:您的颜色映射定义错误。

iris_dataframe["group"]包含['setosa', 'versicolor', 'virginica'].

因此,colors_palete(您的意思是“调色板”吗?)应该是:

colors_palete = {'setosa': "red", 'versicolor': "yellow", 'virginica': "blue"}
于 2019-04-13T13:57:43.807 回答