尝试绘制散点图时为什么会出现KeyError?

时间:2019-04-13 13:54:56

标签: python keyerror iris-dataset

我正在尝试制作一个简单的散点图并获得一个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'```

1 个答案:

答案 0 :(得分:3)

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

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

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

colors_palete = {'setosa': "red", 'versicolor': "yellow", 'virginica': "blue"}
相关问题