Skip to content

BUGfix: reset_index can reset index name (#17067) #17243

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

Closed
wants to merge 5 commits into from
Closed
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
3 changes: 2 additions & 1 deletion doc/source/whatsnew/v0.23.0.txt
Original file line number Diff line number Diff line change
Expand Up @@ -338,7 +338,7 @@ Conversion
- Bug in :class:`Series` floor-division where operating on a scalar ``timedelta`` raises an exception (:issue:`18846`)
- Bug in :class:`FY5253Quarter`, :class:`LastWeekOfMonth` where rollback and rollforward behavior was inconsistent with addition and subtraction behavior (:issue:`18854`)
- Bug in :class:`Index` constructor with ``dtype=CategoricalDtype(...)`` where ``categories`` and ``ordered`` are not maintained (issue:`19032`)
- Bug in :class:`Index` constructor with ``dtype=CategoricalDtype(...)`` where ``categories`` and ``ordered`` are not maintained (issue:`19032`)
- Bug in :class:`Index` constructor with ``dtype=CategoricalDtype(...)`` where ``categories`` and ``ordered`` are not maintained (issue:`19032`)
- Bug in :class:`Series`` with ``dtype='timedelta64[ns]`` where addition or subtraction of ``TimedeltaIndex`` had results cast to ``dtype='int64'`` (:issue:`17250`)
- Bug in :class:`TimedeltaIndex` where division by a ``Series`` would return a ``TimedeltaIndex`` instead of a ``Series`` (issue:`19042`)
- Bug in :class:`Series` with ``dtype='timedelta64[ns]`` where addition or subtraction of ``TimedeltaIndex`` could return a ``Series`` with an incorrect name (issue:`19043`)
Expand All @@ -364,6 +364,7 @@ Indexing
- Bug in :func:`DatetimeIndex.insert` where inserting ``NaT`` into a timezone-aware index incorrectly raised (:issue:`16357`)
- Bug in ``__setitem__`` when indexing a :class:`DataFrame` with a 2-d boolean ndarray (:issue:`18582`)
- Bug in ``str.extractall`` when there were no matches empty :class:`Index` was returned instead of appropriate :class:`MultiIndex` (:issue:`19034`)
- Bug in :func:`Index.__add__` would lose the index name after operations (:issue:`17067`)

I/O
^^^
Expand Down
4 changes: 2 additions & 2 deletions pandas/core/common.py
Original file line number Diff line number Diff line change
Expand Up @@ -205,9 +205,9 @@ def is_bool_indexer(key):
return False


def _default_index(n):
def _default_index(n, name=None):
from pandas.core.index import RangeIndex
return RangeIndex(0, n, name=None)
return RangeIndex(0, n, name=name)


def _mut_exclusive(**kwargs):
Expand Down
2 changes: 1 addition & 1 deletion pandas/core/indexes/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -2141,7 +2141,7 @@ def argsort(self, *args, **kwargs):
return result.argsort(*args, **kwargs)

def __add__(self, other):
return Index(np.array(self) + other)
return Index(np.array(self) + other, name=self.name)
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

actually this is not correct. We don't assign the index name on a boolean operation. only on an inplace operation (e.g. __iadd__). This also would apply to other ops like isub etc.

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@jreback Thank you for your advice on my first pandas PR. :) Should I raise exception in case of

s = pd.Series([1, 2, 3])
s.index.name = 'foo'
s.index += 1
assert s.index.name == 'foo'

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

no, this is slightly complicated. the __iadd__ operator needs to be modified (and not __add__), and corresponding ones.


def __radd__(self, other):
return Index(other + np.array(self))
Expand Down
5 changes: 5 additions & 0 deletions pandas/tests/frame/test_alter_axes.py
Original file line number Diff line number Diff line change
Expand Up @@ -824,6 +824,11 @@ def test_reset_index_range(self):
index=RangeIndex(stop=2))
assert_frame_equal(result, expected)

def test_reset_index_name(self):
# issue `17067`: after reset_index, index name should be None
df = pd.DataFrame(index=pd.Index([], name='x'))
assert df.reset_index(level=[]).index.name is None

def test_set_index_names(self):
df = pd.util.testing.makeDataFrame()
df.index.name = 'name'
Expand Down
8 changes: 8 additions & 0 deletions pandas/tests/indexes/test_base.py
Original file line number Diff line number Diff line change
Expand Up @@ -957,6 +957,14 @@ def test_iadd_string(self):
index += '_x'
assert 'a_x' in index

def test_iadd_index_name(self):
# issue `17067`: test Index keeping index name after plus op
s = pd.Series([1, 2, 3])
s.index.name = 'foo'

s.index += 1
assert s.index.name == 'foo'

def test_difference(self):

first = self.strIndex[5:20]
Expand Down