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

问题描述 投票:2回答:1

我想制作一个简单的散点图并得到一个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'```
python keyerror iris-dataset
1个回答
3
投票

答案很简单:错误地定义了颜色映射。

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

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

colors_palete = {'setosa': "red", 'versicolor': "yellow", 'virginica': "blue"}
© www.soinside.com 2019 - 2024. All rights reserved.