getting this "KeyError: Passing list-likes to .loc or [] with any missing labels is no longer supported"

getting this "KeyError: Passing list-likes to .loc or [] with any missing labels is no longer supported"

当 '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 > 60].iloc[:100]