python - Pandas 数据帧索引 : KeyError:none of [columns] are in the [columns]

标签 python python-3.x pandas

我在 datacamp 的“数据科学中级 Python”。

>>> brics.loc[:]
          country     capital    area   population
BR         Brazil    Brasilia   8.516       200.40
RU         Russia      Moscow  17.100       143.50
IN          India   New Delhi   3.286      1252.00
CH          China     Beijing   9.597      1357.00
SA   South Africa    Pretoria   1.221        52.98
>>> brics.loc[:,['country','capital']]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/local/lib/python3.5/dist-packages/pandas/core/indexing.py", line 1294, in __getitem__
    return self._getitem_tuple(key)
  File "/usr/local/lib/python3.5/dist-packages/pandas/core/indexing.py", line 789, in _getitem_tuple
    self._has_valid_tuple(tup)
  File "/usr/local/lib/python3.5/dist-packages/pandas/core/indexing.py", line 142, in _has_valid_tuple
    if not self._has_valid_type(k, i):
  File "/usr/local/lib/python3.5/dist-packages/pandas/core/indexing.py", line 1379, in _has_valid_type
    (key, self.obj._get_axis_name(axis)))
    KeyError: "None of [['country', 'capital']] are in the [columns]"

这是教科书索引,昨晚有效,但今天无效。
>>> brics.iloc[1,1]
' Moscow'
>>> brics.iloc[1,2]
17.100000000000001

就像我唯一被破坏的函数是 loc(); iloc() 选择得很好。错误消息来自 Pandas ,所以我用 pip3 重新安装;它没有帮助,没有 apt-get update upgrade 等,没有变化。

看起来由于某种原因,pandas 没有在 loc 方法中正确解析我的字符串。

最佳答案

在这里,我使用 .loc 编写了简单的代码你可以看到下面的代码

import pandas as pd
df = pd.DataFrame({'num_legs': [2, 4, 8, 0],'num_wings': [2, 0, 0, 0],'num_specimen_seen': [10, 2, 1, 8]},index=['falcon', 'dog', 'spider', 'fish'])
print(df.loc[:, 'num_legs':'num_wings'])
它在我的情况下有效,你可以试试这个

关于python - Pandas 数据帧索引 : KeyError:none of [columns] are in the [columns],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39244466/

相关文章:

python - Pandas 打印所有 dtypes

python - 如何迭代 Pandas DataFrame 并在另一列中的项目匹配时替换字符串

python - 如何从 PySide QAbstractItemModel 子类向 QML ListView 提供数据?

python - 从具有相同索引的矩阵生成列表

python - GNU/Linux-Python3-PySerial : How to send data over USB connection?

python - 为什么 Python 的内联类方法与元类定义的方法行为不同

python - 不可能在 Selenium 上找到永久覆盖的解决方案

python - 如何在 flask-admin 中引用 ModelView

python - 在 Python 中将维基百科表格抓取为 CSV

python - 如何阅读周三 Oct 02 09 :37:43 BST 2019 to datetime format using pandas?