Python 使用布尔数组作为掩码从数组中选择值时出现无效键错误
我正在尝试运行代码以根据教程生成绘图: 在3-投影到新特征空间中,生成一个Matplot,使用以下代码显示所有三个花:Python 使用布尔数组作为掩码从数组中选择值时出现无效键错误,python,pandas,numpy,matplotlib,pca,Python,Pandas,Numpy,Matplotlib,Pca,我正在尝试运行代码以根据教程生成绘图: 在3-投影到新特征空间中,生成一个Matplot,使用以下代码显示所有三个花: with plt.style.context('seaborn-whitegrid'): plt.figure(figsize=(6, 4)) for lab, col in zip(('Iris-setosa', 'Iris-versicolor', 'Iris-virginica'), ('blue', 'red', 'green')
with plt.style.context('seaborn-whitegrid'):
plt.figure(figsize=(6, 4))
for lab, col in zip(('Iris-setosa', 'Iris-versicolor', 'Iris-virginica'),
('blue', 'red', 'green')):
plt.scatter(Y[y==lab, 0],
Y[y==lab, 1],
label=lab,
c=col)
plt.xlabel('Principal Component 1')
plt.ylabel('Principal Component 2')
plt.legend(loc='lower center')
plt.tight_layout()
plt.show()
当我运行这段代码时,我遇到了以下错误,我不知道如何解决它:
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-12-5a7e436e90e3> in <module>
17 plt.subplot(2, 2, cnt+1)
18 for lab in ('Iris-setosa', 'Iris-versicolor', 'Iris-virginica'):
---> 19 plt.hist(X[y==lab, cnt],
20 label=lab,
21 bins=10,
~/anaconda3/envs/ml/lib/python3.7/site-packages/pandas/core/frame.py in __getitem__(self, key)
2798 if self.columns.nlevels > 1:
2799 return self._getitem_multilevel(key)
-> 2800 indexer = self.columns.get_loc(key)
2801 if is_integer(indexer):
2802 indexer = [indexer]
~/anaconda3/envs/ml/lib/python3.7/site-packages/pandas/core/indexes/base.py in get_loc(self, key, method, tolerance)
2644 )
2645 try:
-> 2646 return self._engine.get_loc(key)
2647 except KeyError:
2648 return self._engine.get_loc(self._maybe_cast_indexer(key))
pandas/_libs/index.pyx in pandas._libs.index.IndexEngine.get_loc()
pandas/_libs/index.pyx in pandas._libs.index.IndexEngine.get_loc()
TypeError: '( class
0 True
1 True
2 True
3 True
4 True
.. ...
145 False
146 False
147 False
148 False
149 False
[150 rows x 1 columns], 0)' is an invalid key
您要更改此设置:
plt.scatter(Y[y==lab, 0],
Y[y==lab, 1],
label=lab,
c=col)
致:
plt.scatter(Y.loc[y==lab, 0],
Y.loc[y==lab, 1],
label=lab,
c=col)