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
Show file tree
Hide file tree
Changes from 5 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 name is None:
name = self.name or 0
result = DataFrame({name: self.values.copy()})

if index:
Expand Down
22 changes: 16 additions & 6 deletions pandas/core/indexes/multi.py
Original file line number Diff line number Diff line change
Expand Up @@ -1126,7 +1126,7 @@ def _to_safe_for_reshape(self):
""" convert to object if we are a categorical """
return self.set_levels([i._to_safe_for_reshape() for i in self.levels])

def to_frame(self, index=True):
def to_frame(self, index=True, names=None):
"""
Create a DataFrame with the levels of the MultiIndex as columns.

Expand All @@ -1143,11 +1143,21 @@ def to_frame(self, index=True):
"""

from pandas import DataFrame
result = DataFrame({(name or level):
self._get_level_values(level)
for name, level in
zip(self.names, range(len(self.levels)))},
copy=False)
if names is not None:
if len(names) != len(self.levels):
raise AssertionError("'names' should have same lenght as "
"number of levels on index")
result = DataFrame({(name):
self._get_level_values(level)
for name, level in
zip(names, range(len(self.levels)))},
copy=False)
else:
result = DataFrame({(name or level):
self._get_level_values(level)
for name, level in
zip(self.names, range(len(self.levels)))},
copy=False)
if index:
result.index = self
return result
Expand Down
11 changes: 11 additions & 0 deletions pandas/tests/indexes/common.py
Original file line number Diff line number Diff line change
Expand Up @@ -81,6 +81,17 @@ def test_to_frame(self):
df = idx.to_frame(index=False)
assert df.index is not idx

new_idx_name = 'new_name'
df = idx.to_frame(name=new_idx_name)

assert df.index is idx
assert len(df.columns) == 1
assert df.columns[0] == new_idx_name
assert df[new_idx_name].values is not idx.values

df = idx.to_frame(index=False, name=new_idx_name)
assert df.index is not idx

def test_shift(self):

# GH8083 test the base class for shift
Expand Down
23 changes: 21 additions & 2 deletions pandas/tests/indexes/multi/test_conversion.py
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,17 @@ def test_to_frame():
expected.index = index
tm.assert_frame_equal(result, expected)

index = MultiIndex.from_tuples(tuples)
result = index.to_frame(index=False, names=['first', 'second'])
expected = DataFrame(tuples)
expected.columns = ['first', 'second']
tm.assert_frame_equal(result, expected)

result = index.to_frame(names=['first', 'second'])
expected.index = index
expected.columns = ['first', 'second']
tm.assert_frame_equal(result, expected)

index = MultiIndex.from_product([range(5),
pd.date_range('20130101', periods=3)])
result = index.to_frame(index=False)
Expand All @@ -45,12 +56,20 @@ def test_to_frame():
1: np.tile(pd.date_range('20130101', periods=3), 5)})
tm.assert_frame_equal(result, expected)

index = MultiIndex.from_product([range(5),
pd.date_range('20130101', periods=3)])
result = index.to_frame()
expected.index = index
tm.assert_frame_equal(result, expected)

result = index.to_frame(index=False, names=['first', 'second'])
expected = DataFrame(
{'first': np.repeat(np.arange(5, dtype='int64'), 3),
'second': np.tile(pd.date_range('20130101', periods=3), 5)})
tm.assert_frame_equal(result, expected)

result = index.to_frame(names=['first', 'second'])
expected.index = index
tm.assert_frame_equal(result, expected)


def test_to_hierarchical():
index = MultiIndex.from_tuples([(1, 'one'), (1, 'two'), (2, 'one'), (
Expand Down