【问题标题】:Pandas Dataframe indexing: KeyError:none of [columns] are in the [columns]Pandas Dataframe 索引:KeyError:[columns] 中没有 [columns]
【发布时间】:2017-01-07 17:46:24
【问题描述】:

我在 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() 选择正常。错误消息来自熊猫,所以我重新安装了 pip3;它没有帮助,没有 apt-get update upgrade 等,没有变化。

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

【问题讨论】:

  • brics.columns 是什么?我认为列名中有空格。然后使用brics.columns = brics.columns.str.strip()
  • 不应该是brics.loc[:, 'country':'capital']吗?
  • @NickilMaveli - 是的,这是另一种解决方案,但 OP 代码也运行良好。
  • jezrael,你是对的,非常感谢。列标签中有空格。

标签: python python-3.x pandas


【解决方案1】:

这里我用.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'])

它在我的情况下工作,你可以试试这个

【讨论】:

    猜你喜欢
    • 2021-11-19
    • 2019-01-29
    • 1970-01-01
    • 1970-01-01
    • 2017-04-05
    • 1970-01-01
    • 1970-01-01
    • 2015-07-27
    • 1970-01-01
    相关资源
    最近更新 更多