【问题标题】:Invalid key Error when selecting Values from an pandas array using a boolean array as mask使用布尔数组作为掩码从熊猫数组中选择值时出现无效键错误
【发布时间】:2020-06-02 20:30:33
【问题描述】:

我正在尝试运行代码以从 this 教程生成绘图: 在Section 3 "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】:

    你想改变这个:

    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)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-05-05
      • 2013-11-27
      • 2020-05-09
      • 2020-11-19
      • 2013-01-17
      • 2020-12-02
      • 1970-01-01
      相关资源
      最近更新 更多