Skip to content

mi.drop(x).get_loc_level(x) returns empty slice (rather than raising KeyError) #22221

Closed
@HuntJSparra

Description

@HuntJSparra

Code Sample

import pandas as pd

df = pd.DataFrame(dict(value=[0, 1], group=['filled','empty']))
groups = df.groupby('group')

def remove1 (group):
	return group[group.value != 1]['value']
trimmed = groups.apply(remove1)


print("Trimmed.loc['empty']:\n",trimmed.loc['empty'])

Problem description

Since Pandas 0.23, if a group (ex. 'empty') is emptied by GroupBy.apply(), then accessing the result (ex. trimmed) through trimmed.loc['empty'] returns the error KeyError: 'the label [empty] is not in the [index]' (full output below). This is possible related to #21624.

Despite what the error says, printing trimmed.indexes shows that 'empty' is a valid index:

MultiIndex(levels=[['empty', 'filled'], [0, 2]],
           labels=[[1, 1], [0, 1]],
           names=['group', None])

Full Output:

Traceback (most recent call last):
  File ".../python3.6/site-packages/pandas/core/indexing.py", line 1790, in _validate_key
    error()
  File ".../python3.6/site-packages/pandas/core/indexing.py", line 1785, in error
    axis=self.obj._get_axis_name(axis)))
KeyError: 'the label [empty] is not in the [index]'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "pandasExample.py", line 14, in <module>
    print("Trimmed.loc['empty']:\n",trimmed.loc['empty'])
  File ".../python3.6/site-packages/pandas/core/indexing.py", line 1478, in __getitem__
    return self._getitem_axis(maybe_callable, axis=axis)
  File ".../python3.6/site-packages/pandas/core/indexing.py", line 1911, in _getitem_axis
    self._validate_key(key, axis)
  File ".../python3.6/site-packages/pandas/core/indexing.py", line 1798, in _validate_key
    error()
  File ".../python3.6/site-packages/pandas/core/indexing.py", line 1785, in error
    axis=self.obj._get_axis_name(axis)))
KeyError: 'the label [empty] is not in the [index]'

Expected Output

Prior to 0.23, an empty Series would be returned.

0.22.0 output:

Trimmed.loc['empty']:
 Series([], Name: value, dtype: int64)

Output of pd.show_versions()

INSTALLED VERSIONS

commit: None
python: 3.6.0.final.0
python-bits: 64
OS: Darwin
OS-release: 17.4.0
machine: x86_64
processor: i386
byteorder: little
LC_ALL: None
LANG: en_US.UTF-8
LOCALE: en_US.UTF-8

pandas: 0.23.3
pytest: 3.6.4
pip: 10.0.1
setuptools: 39.2.0
Cython: None
numpy: 1.15.0
scipy: 1.1.0
pyarrow: None
xarray: None
IPython: 6.5.0
sphinx: 1.7.6
patsy: None
dateutil: 2.7.3
pytz: 2018.5
blosc: None
bottleneck: None
tables: None
numexpr: None
feather: None
matplotlib: None
openpyxl: None
xlrd: None
xlwt: None
xlsxwriter: None
lxml: None
bs4: 4.6.1
html5lib: 1.0.1
sqlalchemy: None
pymysql: None
psycopg2: None
jinja2: 2.10
s3fs: None
fastparquet: None
pandas_gbq: None
pandas_datareader: None

Metadata

Metadata

Assignees

No one assigned

    Labels

    IndexingRelated to indexing on series/frames, not to indexes themselvesMultiIndexNeeds DiscussionRequires discussion from core team before further actionRegressionFunctionality that used to work in a prior pandas version

    Type

    No type

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions