【问题标题】:getting this "KeyError: Passing list-likes to .loc or [] with any missing labels is no longer supported" [duplicate]获取此“KeyError:不再支持将列表喜欢传递给 .loc 或 [] 且缺少任何标签”[重复]
【发布时间】:2021-10-23 11:19:45
【问题描述】:

当“RIDAGEYR”> 60 时,我想从“BPXSY1”的前 100 行的另一个 DataFrame df 中找到创建一个测试 DataFrame df1。

我尝试以下(Python 3.8.8):

df1 = df[df.RIDAGEYR > 60].loc[range(0, 100)]

但是拿回这个:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/Users/wel51x/opt/anaconda3/lib/python3.8/site-packages/pandas/core/indexing.py", line 895, in __getitem__
    return self._getitem_axis(maybe_callable, axis=axis)
  File "/Users/wel51x/opt/anaconda3/lib/python3.8/site-packages/pandas/core/indexing.py", line 1113, in _getitem_axis
    return self._getitem_iterable(key, axis=axis)
  File "/Users/wel51x/opt/anaconda3/lib/python3.8/site-packages/pandas/core/indexing.py", line 1053, in _getitem_iterable
    keyarr, indexer = self._get_listlike_indexer(key, axis, raise_missing=False)
  File "/Users/wel51x/opt/anaconda3/lib/python3.8/site-packages/pandas/core/indexing.py", line 1266, in _get_listlike_indexer
    self._validate_read_indexer(keyarr, indexer, axis, raise_missing=raise_missing)
  File "/Users/wel51x/opt/anaconda3/lib/python3.8/site-packages/pandas/core/indexing.py", line 1321, in _validate_read_indexer
    raise KeyError(
KeyError: "Passing list-likes to .loc or [] with any missing labels is no longer supported. The following labels were missing: Int64Index([ 0,  2,  4,  5,  7,\n            ...\n            95, 96, 97, 98, 99],\n           dtype='int64', length=72). See https://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#deprecate-loc-reindex-listlike"

通过阅读其他人所写的内容,我意识到当他们遇到类似问题需要重新索引时;然而,许多不同的修复尝试都会产生相同的结果。

非常感谢任何帮助。

【问题讨论】:

  • 是的,我试过了,但到目前为止还没有为我解决。
  • df1 = df[df.RIDAGEYR &gt; 60].head(100) 可能是解决此问题的更常见方法。
  • @Henry Ecker - 谢谢

标签: python pandas slice keyerror


【解决方案1】:

也许试试吧:

df1 = df[df.RIDAGEYR > 60].iloc[:100]

【讨论】:

  • 你成功了!知道为什么我的失败了吗?
  • @WinstonLee 这是因为loc 不用于索引... :) 请接受并投票 :)
  • 两者都已完成。
猜你喜欢
  • 2021-03-05
  • 2021-07-21
  • 2020-07-06
  • 2021-07-18
  • 2020-12-24
  • 2021-04-24
  • 1970-01-01
  • 2021-04-21
相关资源
最近更新 更多