BUG: xs not working with slice · Issue #35301 · pandas-dev/pandas (original) (raw)

Code Sample, a copy-pastable example

data = """ C1 C2 V A1 0 10 A1 1 20 A2 0 2 A2 1 3 B1 0 2 B2 1 3 """

import pandas as pd from io import StringIO df = pd.read_csv(StringIO(data), sep=' +').set_index(['C1', 'C2'])

df.xs(pd.IndexSlice['A1', :])

Problem description

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/home/***/lib/python3.7/site-packages/pandas/core/generic.py", line 3535, in xs
    loc, new_index = self.index.get_loc_level(key, drop_level=drop_level)
  File "/home/***/lib/python3.7/site-packages/pandas/core/indexes/multi.py", line 2835, in get_loc_level
    raise TypeError(key)
TypeError: ('A1', slice(None, None, None))

also similar code produce the same problem (df.xs(('A1', slice(None)))). Strangely this works:

df = pd.DataFrame({'a': [1, 2, 3, 1], 'b': ['a', 'b', 'c', 'd'], 'v': [2, 3, 4, 5]}).set_index(['a', 'b']) df.xs(pd.IndexSlice[1, :])

Output of pd.show_versions()

INSTALLED VERSIONS ------------------ commit : None python : 3.7.7.final.0 python-bits : 64 OS : Linux OS-release : 5.7.7-100.fc31.x86_64 machine : x86_64 processor : x86_64 byteorder : little LC_ALL : None LANG : it_IT.UTF-8 LOCALE : it_IT.UTF-8

pandas : 1.0.5
numpy : 1.19.0
pytz : 2019.2
dateutil : 2.7.5
pip : 20.1.1
setuptools : 41.6.0
Cython : 0.29.15
pytest : 4.0.0
hypothesis : None
sphinx : 3.1.1
blosc : None
feather : None
xlsxwriter : None
lxml.etree : 4.4.0
html5lib : 1.0.1
pymysql : None
psycopg2 : None
jinja2 : 2.10
IPython : 7.16.1
pandas_datareader: 0.8.0
bs4 : 4.7.1
bottleneck : 1.2.1
fastparquet : None
gcsfs : None
lxml.etree : 4.4.0
matplotlib : 3.2.2
numexpr : 2.7.1
odfpy : None
openpyxl : None
pandas_gbq : None
pyarrow : None
pytables : None
pytest : 4.0.0
pyxlsb : None
s3fs : 0.4.2
scipy : 1.5.1
sqlalchemy : None
tables : 3.5.2
tabulate : 0.8.5
xarray : 0.12.1
xlrd : 1.2.0
xlwt : 1.1.2
xlsxwriter : None
numba : 0.48.0