Skip to content
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

ENH: Add Index.to_frame method #17815

Merged
merged 1 commit into from
Oct 9, 2017
Merged
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: 3 additions & 0 deletions doc/source/api.rst
Original file line number Diff line number Diff line change
Expand Up @@ -1376,6 +1376,7 @@ Conversion
Index.tolist
Index.to_datetime
Index.to_series
Index.to_frame

Sorting
~~~~~~~
Expand Down Expand Up @@ -1591,6 +1592,7 @@ Conversion
DatetimeIndex.to_perioddelta
DatetimeIndex.to_pydatetime
DatetimeIndex.to_series
DatetimeIndex.to_frame

TimedeltaIndex
--------------
Expand Down Expand Up @@ -1623,6 +1625,7 @@ Conversion
TimedeltaIndex.round
TimedeltaIndex.floor
TimedeltaIndex.ceil
TimedeltaIndex.to_frame

.. currentmodule:: pandas

Expand Down
1 change: 1 addition & 0 deletions doc/source/whatsnew/v0.21.0.txt
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@ New features
- Added ``skipna`` parameter to :func:`~pandas.api.types.infer_dtype` to
support type inference in the presence of missing values (:issue:`17059`).
- :class:`~pandas.Resampler.nearest` is added to support nearest-neighbor upsampling (:issue:`17496`).
- :class:`~pandas.Index` has added support for a ``to_frame`` method (:issue:`15230`)

.. _whatsnew_0210.enhancements.infer_objects:

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 @@ -1005,6 +1005,29 @@ def to_series(self, **kwargs):
index=self._shallow_copy(),
name=self.name)

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

.. versionadded:: 0.21.0

Parameters
----------
index : boolean, default True
Set the index of the returned DataFrame as the original Index.

Returns
-------
DataFrame : a DataFrame containing the original Index data.
"""

from pandas import DataFrame
Copy link
Contributor

Choose a reason for hiding this comment

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

this does not do the same thing as .to_series() where the values and the index are the same.
is there a reason you are doing this?

Copy link
Member Author

@gfyoung gfyoung Oct 8, 2017

Choose a reason for hiding this comment

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

where the values and the index are the same.

Not sure I get you here. The implementation I wrote tries to be consistent with what was done with MultiIndex by constructing DataFrame with data and setting the index if needed.

Copy link
Contributor

Choose a reason for hiding this comment

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

ok this is reasonable, side issue this is a little suspect:

In [4]: pd.MultiIndex.from_product([range(3),list('ab')], names=['foo', 'bar']).to_frame()
Out[4]: 
        bar  foo
foo bar         
0   a     a    0
    b     b    0
1   a     a    1
    b     b    1
2   a     a    2
    b     b    2

In [5]: pd.MultiIndex.from_product([range(3),list('ab')], names=['foo', 'bar']).to_series()
Out[5]: 
foo  bar
0    a      (0, a)
     b      (0, b)
1    a      (1, a)
     b      (1, b)
2    a      (2, a)
     b      (2, b)
dtype: object

Copy link
Member

Choose a reason for hiding this comment

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

What is suspect about it?
The index seems toe same in both examples?

result = DataFrame(self._shallow_copy(), columns=[self.name or 0])

if index:
result.index = self
return result

def _to_embed(self, keep_tz=False):
"""
*this is an internal non-public method*
Expand Down
40 changes: 40 additions & 0 deletions pandas/core/indexes/datetimes.py
Original file line number Diff line number Diff line change
Expand Up @@ -915,6 +915,46 @@ def to_series(self, keep_tz=False):
index=self._shallow_copy(),
name=self.name)

def to_frame(self, index=True, keep_tz=False):
"""
Create a DataFrame with a column containing the DatetimeIndex.

.. versionadded:: 0.21.0

Parameters
----------
index : boolean, default True
Set the index of the returned DataFrame
as the original DatetimeIndex.

keep_tz : optional, defaults False.
return the data keeping the timezone.

If keep_tz is True:

If the timezone is not set, the resulting
Series will have a datetime64[ns] dtype.

Otherwise the DataFrame will have an datetime64[ns, tz] dtype;
the tz will be preserved.

If keep_tz is False:

DataFrame will have a datetime64[ns] dtype. TZ aware
objects will have the tz removed.

Returns
-------
DataFrame : a DataFrame containing the original DatetimeIndex data.
"""

from pandas import DataFrame
result = DataFrame(self._to_embed(keep_tz), columns=[self.name or 0])

if index:
result.index = self
return result

def _to_embed(self, keep_tz=False):
"""
return an array repr of this object, potentially casting to object
Expand Down
6 changes: 3 additions & 3 deletions pandas/core/indexes/multi.py
Original file line number Diff line number Diff line change
Expand Up @@ -1010,18 +1010,18 @@ def _to_safe_for_reshape(self):

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

.. versionadded:: 0.20.0

Parameters
----------
index : boolean, default True
return this MultiIndex as the index
Set the index of the returned DataFrame as the original MultiIndex.

Returns
-------
DataFrame
DataFrame : a DataFrame containing the original MultiIndex data.
"""

from pandas import DataFrame
Expand Down
15 changes: 15 additions & 0 deletions pandas/tests/indexes/common.py
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,21 @@ def test_to_series(self):
assert s.index is not idx
assert s.name == idx.name

def test_to_frame(self):
# see gh-15230
idx = self.create_index()
name = idx.name or 0
Copy link
Member

Choose a reason for hiding this comment

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

There is at least one in the create_index indices that has a name? (or at least one that has no name)

Copy link
Member Author

Choose a reason for hiding this comment

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

Yes, there is.


df = idx.to_frame()

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

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

def test_shift(self):

# GH8083 test the base class for shift
Expand Down