Skip to content

REGR: DataFrame.reset_index with empty RangeIndex #45377

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Jan 16, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 8 additions & 2 deletions pandas/core/indexes/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -2081,8 +2081,14 @@ def _drop_level_numbers(self, levnums: list[int]):

if len(lev) == 0:
# If lev is empty, lev.take will fail GH#42055
res_values = algos.take(lev._values, new_codes[0], allow_fill=True)
result = type(lev)._simple_new(res_values, name=new_names[0])
if len(new_codes[0]) == 0:
# GH#45230 preserve RangeIndex here
# see test_reset_index_empty_rangeindex
result = lev[:0]
else:
res_values = algos.take(lev._values, new_codes[0], allow_fill=True)
# _constructor instead of type(lev) for RangeIndex compat GH#35230
result = lev._constructor._simple_new(res_values, name=new_names[0])
else:
# set nan if needed
mask = new_codes[0] == -1
Expand Down
11 changes: 11 additions & 0 deletions pandas/tests/frame/methods/test_reset_index.py
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,17 @@


class TestResetIndex:
def test_reset_index_empty_rangeindex(self):
# GH#45230
df = DataFrame(
columns=["brand"], dtype=np.int64, index=RangeIndex(0, 0, 1, name="foo")
)

df2 = df.set_index([df.index, "brand"])

result = df2.reset_index([1], drop=True)
tm.assert_frame_equal(result, df[[]], check_index_type=True)

def test_set_reset(self):

idx = Index([2 ** 63, 2 ** 63 + 5, 2 ** 63 + 10], name="foo")
Expand Down