当使用布尔数组作为掩码从pandas数组中选择值时,出现无效键错误。

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

我试图运行代码来生成一个来自于 这个 教程:在 第三节 "3 - Projection Onto the New Feature Space "生成了一个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')):
    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
python pandas numpy matplotlib pca
1个回答
0
投票

你想改变这个。

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)
© www.soinside.com 2019 - 2024. All rights reserved.