Search code examples
pythonpandasslicekeyerror

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


I want to find create a test DataFrame df1 from another DataFrame df of the first 100 rows of 'BPXSY1' when 'RIDAGEYR' > 60.

I try the following (Python 3.8.8):

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

but get back this:

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"

I am aware from reading what others have written when they have a similar problem that I need to re-index; however a number of different attempts at a fix all produce the same result.

Any help is greatly appreciated.


Solution

  • Maybe just try:

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