Skip to content

Bug fix - rename dataframe reset index #46167

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 88 commits into from
Mar 29, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
88 commits
Select commit Hold shift + click to select a range
f75fd19
Update frame.py
Feb 27, 2022
bf9b3de
Update base.py
Feb 27, 2022
e4665ab
Update test_reset_index.py
Feb 27, 2022
bdb010f
Update v1.5.0.rst
Feb 27, 2022
7871c05
add
Feb 27, 2022
0166c9d
Update frame.py
Feb 27, 2022
cb460d7
Update frame.py
Feb 27, 2022
5fe7c1b
pre-commit
Feb 27, 2022
0fde54b
Merge branch 'main' into bug_fix_rename_dataframe_reset_index
Feb 27, 2022
638182a
add
Mar 3, 2022
e19d807
reset index
Mar 5, 2022
bccb825
Docstring and typing validation
Mar 5, 2022
a328d9b
Update frame.py
Mar 6, 2022
4392233
Update base.py
Mar 6, 2022
18e36c8
Update test_reset_index.py
Mar 6, 2022
6229168
remove is_array_like
Mar 6, 2022
42bdfda
docstring
Mar 8, 2022
dffa501
docstring
Mar 8, 2022
b210e93
Merge branch 'main' of https://github.com/weikhor/pandas into bug_fix…
Mar 8, 2022
8856572
docstring
Mar 8, 2022
b4aa34b
Merge branch 'main' into bug_fix_rename_dataframe_reset_index
Mar 9, 2022
647b526
Merge branch 'main' into bug_fix_rename_dataframe_reset_index
Mar 10, 2022
6b5a76b
add none to default
Mar 10, 2022
c79cb09
remove return type of string
Mar 10, 2022
776dea8
Merge branch 'main' into bug_fix_rename_dataframe_reset_index
Mar 11, 2022
1ccb5ab
Update frame.py
Mar 11, 2022
bdf7691
pre commit
Mar 11, 2022
dbe2ec3
add return type
Mar 11, 2022
7002639
type
Mar 11, 2022
aad0759
Merge branch 'main' of https://github.com/weikhor/pandas into bug_fix…
Mar 11, 2022
29fe527
Merge branch 'main' of https://github.com/weikhor/pandas into bug_fix…
Mar 12, 2022
98865a7
doc
Mar 12, 2022
9cbe1ed
Merge branch 'main' into bug_fix_rename_dataframe_reset_index
Mar 13, 2022
4d473d8
Merge branch 'main' of https://github.com/weikhor/pandas into bug_fix…
Mar 14, 2022
fac0e7f
Merge branch 'bug_fix_rename_dataframe_reset_index' of https://github…
Mar 14, 2022
27cbb62
doc
Mar 14, 2022
5efd2eb
doc
Mar 14, 2022
1148e46
frame
Mar 14, 2022
e924d06
doc
Mar 14, 2022
db2626a
doc
Mar 16, 2022
2e136ac
Merge branch 'main' of https://github.com/weikhor/pandas into bug_fix…
Mar 16, 2022
5d2dda2
pre commit
Mar 16, 2022
540e4f9
doc
Mar 16, 2022
14564e8
Merge branch 'main' into bug_fix_rename_dataframe_reset_index
jreback Mar 18, 2022
4c00430
Update frame.py
Mar 19, 2022
106beb8
Merge branch 'main' into bug_fix_rename_dataframe_reset_index
Mar 19, 2022
e30dd14
pre commit
Mar 19, 2022
8b61ced
Update frame.py
Mar 19, 2022
d3b2444
Update frame.py
Mar 19, 2022
775bfea
Update frame.py
Mar 19, 2022
f5a59cd
pre commit
Mar 19, 2022
d77868f
df doc
Mar 20, 2022
9e4bfd1
Merge branch 'main' of https://github.com/weikhor/pandas into bug_fix…
Mar 20, 2022
a4d5a76
df doc
Mar 20, 2022
89a0ad7
rst
Mar 20, 2022
d80107d
Update v1.5.0.rst
Mar 20, 2022
247d490
Update v1.5.0.rst
Mar 20, 2022
ad19646
Update frame.py
Mar 20, 2022
3efafaf
pre commit
Mar 20, 2022
2e16d96
Merge branch 'main' into bug_fix_rename_dataframe_reset_index
Mar 20, 2022
4967381
Merge branch 'main' of https://github.com/weikhor/pandas into bug_fix…
Mar 21, 2022
d614da0
remove doc
Mar 21, 2022
8af651a
add
Mar 21, 2022
b47adb5
test remove first
Mar 22, 2022
ce44104
Merge branch 'main' into bug_fix_rename_dataframe_reset_index
Mar 22, 2022
175ab70
remove
Mar 22, 2022
aa583ee
test
Mar 22, 2022
0111d4d
doc
Mar 22, 2022
bfc48f9
Merge branch 'main' of https://github.com/weikhor/pandas into bug_fix…
Mar 22, 2022
0c61012
Merge branch 'bug_fix_rename_dataframe_reset_index' of https://github…
Mar 22, 2022
11085c7
add
Mar 22, 2022
abfb95d
doc
Mar 22, 2022
0086bd5
add
Mar 22, 2022
7778d4b
Update base.py
Mar 22, 2022
1428894
doc
Mar 22, 2022
d1bc3eb
Merge branch 'bug_fix_rename_dataframe_reset_index' of https://github…
Mar 22, 2022
d2939c5
doc
Mar 22, 2022
ca641f6
add methods
Mar 23, 2022
51b0724
add
Mar 23, 2022
2dd795b
Merge branch 'main' into bug_fix_rename_dataframe_reset_index
Mar 23, 2022
d081072
Merge branch 'main' into bug_fix_rename_dataframe_reset_index
Mar 25, 2022
2de3426
Merge branch 'main' into bug_fix_rename_dataframe_reset_index
Mar 27, 2022
83e81a6
doc
Mar 27, 2022
774a509
doc
Mar 27, 2022
2e99a82
doc
Mar 27, 2022
6e95d09
Merge branch 'main' into bug_fix_rename_dataframe_reset_index
Mar 28, 2022
9b2deb5
add test
Mar 29, 2022
ad2d8eb
Merge branch 'main' into bug_fix_rename_dataframe_reset_index
Mar 29, 2022
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
2 changes: 1 addition & 1 deletion doc/source/whatsnew/v1.5.0.rst
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,7 @@ Other enhancements
- Improved error message in :class:`~pandas.core.window.Rolling` when ``window`` is a frequency and ``NaT`` is in the rolling axis (:issue:`46087`)
- :class:`Series` and :class:`DataFrame` with ``IntegerDtype`` now supports bitwise operations (:issue:`34463`)
- Add ``milliseconds`` field support for :class:`~pandas.DateOffset` (:issue:`43371`)
-
- :meth:`DataFrame.reset_index` now accepts a ``names`` argument which renames the index names (:issue:`6878`)

.. ---------------------------------------------------------------------------
.. _whatsnew_150.notable_bug_fixes:
Expand Down
31 changes: 28 additions & 3 deletions pandas/core/frame.py
Original file line number Diff line number Diff line change
Expand Up @@ -5684,6 +5684,7 @@ def reset_index(
col_level: Hashable = ...,
col_fill: Hashable = ...,
allow_duplicates: bool | lib.NoDefault = ...,
names: Hashable | Sequence[Hashable] = None,
) -> DataFrame:
...

Expand All @@ -5696,6 +5697,7 @@ def reset_index(
col_level: Hashable = ...,
col_fill: Hashable = ...,
allow_duplicates: bool | lib.NoDefault = ...,
names: Hashable | Sequence[Hashable] = None,
) -> None:
...

Expand All @@ -5708,6 +5710,7 @@ def reset_index(
col_level: Hashable = ...,
col_fill: Hashable = ...,
allow_duplicates: bool | lib.NoDefault = ...,
names: Hashable | Sequence[Hashable] = None,
) -> None:
...

Expand All @@ -5720,6 +5723,7 @@ def reset_index(
col_level: Hashable = ...,
col_fill: Hashable = ...,
allow_duplicates: bool | lib.NoDefault = ...,
names: Hashable | Sequence[Hashable] = None,
) -> None:
...

Expand All @@ -5731,6 +5735,7 @@ def reset_index(
col_level: Hashable = ...,
col_fill: Hashable = ...,
allow_duplicates: bool | lib.NoDefault = ...,
names: Hashable | Sequence[Hashable] = None,
) -> None:
...

Expand All @@ -5743,6 +5748,7 @@ def reset_index(
col_level: Hashable = ...,
col_fill: Hashable = ...,
allow_duplicates: bool | lib.NoDefault = ...,
names: Hashable | Sequence[Hashable] = None,
) -> DataFrame | None:
...

Expand All @@ -5755,6 +5761,7 @@ def reset_index(
col_level: Hashable = 0,
col_fill: Hashable = "",
allow_duplicates: bool | lib.NoDefault = lib.no_default,
names: Hashable | Sequence[Hashable] = None,
) -> DataFrame | None:
"""
Reset the index, or a level of it.
Expand Down Expand Up @@ -5785,6 +5792,13 @@ def reset_index(

.. versionadded:: 1.5.0

names : int, str or 1-dimensional list, default None
Using the given string, rename the DataFrame column which contains the
index data. If the DataFrame has a MultiIndex, this has to be a list or
tuple with length equal to the number of levels.

.. versionadded:: 1.5.0

Returns
-------
DataFrame or None
Expand Down Expand Up @@ -5855,6 +5869,16 @@ class name
mammal lion 80.5 run
monkey NaN jump

Using the `names` parameter, choose a name for the index column:

>>> df.reset_index(names=['classes', 'names'])
classes names speed species
max type
0 bird falcon 389.0 fly
1 bird parrot 24.0 fly
2 mammal lion 80.5 run
3 mammal monkey NaN jump

If the index has multiple levels, we can reset a subset of them:

>>> df.reset_index(level='class')
Expand Down Expand Up @@ -5920,12 +5944,13 @@ class max type

if not drop:
to_insert: Iterable[tuple[Any, Any | None]]

default = "index" if "index" not in self else "level_0"
names = self.index._get_default_index_names(names, default)

if isinstance(self.index, MultiIndex):
names = com.fill_missing_names(self.index.names)
to_insert = zip(self.index.levels, self.index.codes)
else:
default = "index" if "index" not in self else "level_0"
names = [default] if self.index.name is None else [self.index.name]
to_insert = ((self.index, None),)

multi_col = isinstance(self.columns, MultiIndex)
Expand Down
35 changes: 35 additions & 0 deletions pandas/core/indexes/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -1771,6 +1771,41 @@ def _validate_names(

return new_names

def _get_default_index_names(
self, names: Hashable | Sequence[Hashable] | None = None, default=None
) -> list[Hashable]:
"""
Get names of index.

Parameters
----------
names : int, str or 1-dimensional list, default None
Index names to set.
default : str
Default name of index.

Raises
------
TypeError
if names not str or list-like
"""
from pandas.core.indexes.multi import MultiIndex

if names is not None:
if isinstance(names, str) or isinstance(names, int):
names = [names]

if not isinstance(names, list) and names is not None:
raise ValueError("Index names must be str or 1-dimensional list")

if not names:
if isinstance(self, MultiIndex):
names = com.fill_missing_names(self.names)
else:
names = [default] if self.name is None else [self.name]

return names

def _get_names(self) -> FrozenList:
return FrozenList((self.name,))

Expand Down
39 changes: 39 additions & 0 deletions pandas/tests/frame/methods/test_reset_index.py
Original file line number Diff line number Diff line change
Expand Up @@ -754,3 +754,42 @@ def test_reset_index_interval_columns_object_cast():
columns=Index(["Year", Interval(0, 1), Interval(1, 2)]),
)
tm.assert_frame_equal(result, expected)


def test_reset_index_rename(float_frame):
# GH 6878
result = float_frame.reset_index(names="new_name")
expected = Series(float_frame.index.values, name="new_name")
tm.assert_series_equal(result["new_name"], expected)

result = float_frame.reset_index(names=123)
expected = Series(float_frame.index.values, name=123)
tm.assert_series_equal(result[123], expected)


def test_reset_index_rename_multiindex(float_frame):
# GH 6878
stacked_df = float_frame.stack()[::2]
stacked_df = DataFrame({"foo": stacked_df, "bar": stacked_df})

names = ["first", "second"]
stacked_df.index.names = names

result = stacked_df.reset_index()
expected = stacked_df.reset_index(names=["new_first", "new_second"])
tm.assert_series_equal(result["first"], expected["new_first"], check_names=False)
tm.assert_series_equal(result["second"], expected["new_second"], check_names=False)


def test_errorreset_index_rename(float_frame):
# GH 6878
stacked_df = float_frame.stack()[::2]
stacked_df = DataFrame({"first": stacked_df, "second": stacked_df})

with pytest.raises(
Copy link
Contributor

Choose a reason for hiding this comment

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

can you make a new test for the errors tests. add one that tests an Index with names = list-like

Copy link
Contributor Author

Choose a reason for hiding this comment

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

Have add test.

ValueError, match="Index names must be str or 1-dimensional list"
):
stacked_df.reset_index(names={"first": "new_first", "second": "new_second"})

with pytest.raises(IndexError, match="list index out of range"):
stacked_df.reset_index(names=["new_first"])