BUG: MultiIndex slicing with negative step by lukemanley · Pull Request #46156 · pandas-dev/pandas (original) (raw)
- Tests added and passed if fixing a bug or adding a new feature
- All code checks passed.
- Added an entry in the latest
doc/source/whatsnew/v1.5.0.rst
file if fixing a bug or adding a new feature.
MultiIndex label-based (.loc) slicing with a negative step size appears to contain a few bugs.
#38071 may have partially addressed negative step size issues, but a few issues seem to remain.
I believe this PR fixes the following:
Bug 1: slicing with non-null start/stop values returns an empty frame
from pandas import DataFrame, IndexSlice, MultiIndex
mi = MultiIndex.from_arrays([range(5)] * 2)
df = DataFrame(1.0, index=mi, columns=['A'])
target = IndexSlice[3:1:-1, :]
df.loc[target, :]
Bug 2: negative step size other than -1 raises
from pandas import DataFrame, IndexSlice, MultiIndex
mi = MultiIndex.from_arrays([range(5)] * 2)
df = DataFrame(1.0, index=mi, columns=['A'])
target = IndexSlice[::-2, :]
df.loc[target, :]
Bug 3: slicing a non-int labeled index level raises
from pandas import DataFrame, IndexSlice, MultiIndex
mi = MultiIndex.from_arrays([list('abcde')] * 2)
df = DataFrame(1.0, index=mi, columns=['A'])
target = IndexSlice['d':'b':-1, :]
df.loc[target, :]
The tests have been expanded to cover these cases.