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 12 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 @@ -41,7 +41,7 @@ Other enhancements
- Implemented a ``bool``-dtype :class:`Index`, passing a bool-dtype array-like to ``pd.Index`` will now retain ``bool`` dtype instead of casting to ``object`` (:issue:`45061`)
- Implemented a complex-dtype :class:`Index`, passing a complex-dtype array-like to ``pd.Index`` will now retain complex dtype instead of casting to ``object`` (:issue:`45845`)
- :class:`Series` and :class:`DataFrame` with ``IntegerDtype`` now supports bitwise operations (:issue:`34463`)
-
- :meth:`DataFrame.reset_index` now accepts a ``names`` argument which renames the index names (:issue:`6878`)

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

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

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

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

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

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

Expand All @@ -5696,6 +5702,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 @@ -5723,6 +5730,10 @@ def reset_index(
levels are named. If None then the index name is repeated.
allow_duplicates : bool, optional, default lib.no_default
Allow duplicate column labels to be created.
names : str, tuple or 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

Expand Down Expand Up @@ -5841,6 +5852,15 @@ class max type
parrot bird 24.0 fly
lion mammal 80.5 run
monkey mammal NaN jump

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

>>> df.reset_index(names='name')
name class max_speed
0 falcon bird 389.0
1 parrot bird 24.0
2 lion mammal 80.5
3 monkey mammal NaN
"""
inplace = validate_bool_kwarg(inplace, "inplace")
self._check_inplace_and_allows_duplicate_labels(inplace)
Expand All @@ -5861,12 +5881,12 @@ 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
23 changes: 23 additions & 0 deletions pandas/core/indexes/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -1765,6 +1765,29 @@ def _validate_names(

return new_names

def get_default_index_names(self, names=None, default=None) -> Sequence[str]:
from pandas.core.indexes.multi import MultiIndex

# if names is not None and not all(isinstance(name, str) for name in names):
# raise ValueError("Names must be a string")
if names is not None:
if isinstance(names, str):
names = [names]
elif isinstance(names, list) and not all(
isinstance(name, str) for name in names
):
raise ValueError("Names must be a string")
elif not (isinstance(names, list) and not isinstance(names, str)):
raise ValueError("Names must be a string or 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
27 changes: 27 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,30 @@ 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)

with pytest.raises(ValueError, match="Names must be a string"):
float_frame.reset_index(names=1)


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)

with pytest.raises(ValueError, match="Names must be a string or list"):
stacked_df.reset_index(names={"first": "new_first", "second": "new_second"})