Skip to content

Add 'name' as argument for index 'to_frame' method #22580

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
Changes from 2 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
15 changes: 13 additions & 2 deletions pandas/core/indexes/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -1116,7 +1116,7 @@ def to_series(self, index=None, name=None):

return Series(self._to_embed(), index=index, name=name)

def to_frame(self, index=True):
def to_frame(self, index=True, name=None):
"""
Create a DataFrame with a column containing the Index.

Expand All @@ -1127,6 +1127,10 @@ def to_frame(self, index=True):
index : boolean, default True
Set the index of the returned DataFrame as the original Index.

name : object, default None
The passed name should substitute for the series name (if it has
Copy link
Contributor

Choose a reason for hiding this comment

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

'series' -> 'index'

one).

Returns
-------
DataFrame
Expand Down Expand Up @@ -1154,10 +1158,17 @@ def to_frame(self, index=True):
0 Ant
1 Bear
2 Cow

>>> idx.to_frame(index=False, name='zoo')
zoo
0 Ant
1 Bear
2 Cow
"""

from pandas import DataFrame
name = self.name or 0
if not name:
Copy link
Contributor

Choose a reason for hiding this comment

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

This would have to be if name is not None, to allow falsey names.

Copy link
Contributor Author

Choose a reason for hiding this comment

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

You are right! I will change that

name = self.name or 0
result = DataFrame({name: self.values.copy()})

if index:
Expand Down