Incoherence between Index and MultiIndex when labels in list are not found · Issue #15452 · pandas-dev/pandas (original) (raw)

Code Sample, a copy-pastable example if possible

In [2]: s = pd.Series(range(4), index=pd.MultiIndex.from_product([[1,2], ['a', 'b']]))

In [3]: s.loc[['not', 'found']] Out[3]: Series([], dtype: int64)

Problem description

With regular Indexes, looking for a list of labels of which none is present will raise KeyError (see below). We should be coherent (and while I would prefer the empty result to the exception, this was already discussed in #7999).

Expected Output

Compare to

In [4]: s.reset_index().loc[['not', 'found']]

KeyError Traceback (most recent call last) in () ----> 1 s.reset_index().loc[['not', 'found']]

/home/nobackup/repo/pandas/pandas/core/indexing.py in getitem(self, key) 1339 else: 1340 key = com._apply_if_callable(key, self.obj) -> 1341 return self._getitem_axis(key, axis=0) 1342 1343 def _is_scalar_access(self, key):

/home/nobackup/repo/pandas/pandas/core/indexing.py in _getitem_axis(self, key, axis) 1539 raise ValueError('Cannot index with multidimensional key') 1540 -> 1541 return self._getitem_iterable(key, axis=axis) 1542 1543 # nested tuple slicing

/home/nobackup/repo/pandas/pandas/core/indexing.py in _getitem_iterable(self, key, axis) 1049 def _getitem_iterable(self, key, axis=0): 1050 if self._should_validate_iterable(axis): -> 1051 self._has_valid_type(key, axis) 1052 1053 labels = self.obj._get_axis(axis)

/home/nobackup/repo/pandas/pandas/core/indexing.py in _has_valid_type(self, key, axis) 1429 1430 raise KeyError("None of [%s] are in the [%s]" % -> 1431 (key, self.obj._get_axis_name(axis))) 1432 1433 return True

KeyError: "None of [['not', 'found']] are in the [index]"

Output of pd.show_versions()

INSTALLED VERSIONS ------------------ commit: f65a641python: 3.5.2.final.0 python-bits: 64 OS: Linux OS-release: 4.7.0-1-amd64 machine: x86_64 processor: byteorder: little LC_ALL: None LANG: it_IT.utf8 LOCALE: it_IT.UTF-8

pandas: 0.19.0+473.gf65a641
pytest: 3.0.6
pip: 8.1.2
setuptools: 28.0.0
Cython: 0.23.4
numpy: 1.12.0
scipy: 0.18.1
xarray: None
IPython: 5.1.0.dev
sphinx: 1.4.8
patsy: 0.3.0-dev
dateutil: 2.5.3
pytz: 2015.7
blosc: None
bottleneck: 1.2.0
tables: 3.2.2
numexpr: 2.6.0
feather: None
matplotlib: 2.0.0rc2
openpyxl: 2.3.0
xlrd: 1.0.0
xlwt: 1.1.2
xlsxwriter: 0.9.3
lxml: 3.6.4
bs4: 4.5.1
html5lib: 0.999
httplib2: 0.9.1
apiclient: 1.5.2
sqlalchemy: 1.0.15
pymysql: None
psycopg2: None
jinja2: 2.8
s3fs: None
pandas_datareader: 0.2.1