Skip to content

MultiIndex Support for DataFrame.pivot #25330

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

Closed
wants to merge 21 commits into from
Closed
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
13 changes: 13 additions & 0 deletions doc/source/user_guide/reshaping.rst
Original file line number Diff line number Diff line change
Expand Up @@ -90,6 +90,19 @@ You can then select subsets from the pivoted ``DataFrame``:
Note that this returns a view on the underlying data in the case where the data
are homogeneously-typed.

Now :meth:`DataFrame.pivot` method also supports multiple columns as indexes.
Copy link
Member

Choose a reason for hiding this comment

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

Add a versionadded tag here.


.. ipython:: python

df1 = pd.DataFrame({'variable1': ['A', 'A', 'A', 'A', 'B', 'B', 'B', 'B'],
'variable2': ['a', 'a', 'b', 'b', 'a', 'a', 'b', 'b'],
'variable3': ['C', 'D', 'C', 'D', 'C', 'D', 'C', 'D'],
'value': np.arange(8)})
df1

df1.pivot(index=['variable1', 'variable2'], columns='variable3',
values='value')

.. note::
:func:`~pandas.pivot` will error with a ``ValueError: Index contains duplicate
entries, cannot reshape`` if the index/column pair is not unique. In this
Expand Down
1 change: 1 addition & 0 deletions doc/source/whatsnew/v0.25.0.rst
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@ Other Enhancements
- Indexing of ``DataFrame`` and ``Series`` now accepts zerodim ``np.ndarray`` (:issue:`24919`)
- :meth:`Timestamp.replace` now supports the ``fold`` argument to disambiguate DST transition times (:issue:`25017`)
- :meth:`DataFrame.at_time` and :meth:`Series.at_time` now support :meth:`datetime.time` objects with timezones (:issue:`24043`)
- :meth:`DataFrame.pivot` now supports multiple column indexes by accepting a list of columns (:issue:`21425`)
- ``Series.str`` has gained :meth:`Series.str.casefold` method to removes all case distinctions present in a string (:issue:`25405`)
- :meth:`DataFrame.set_index` now works for instances of ``abc.Iterator``, provided their output is of the same length as the calling frame (:issue:`22484`, :issue:`24984`)
- :meth:`DatetimeIndex.union` now supports the ``sort`` argument. The behaviour of the sort parameter matches that of :meth:`Index.union` (:issue:`24994`)
Expand Down
24 changes: 20 additions & 4 deletions pandas/core/reshape/pivot.py
Original file line number Diff line number Diff line change
Expand Up @@ -368,18 +368,34 @@ def _convert_by(by):
@Appender(_shared_docs['pivot'], indents=1)
Copy link
Member

Choose a reason for hiding this comment

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

Also think you will need to update the docstring

def pivot(data, index=None, columns=None, values=None):
if values is None:
cols = [columns] if index is None else [index, columns]
# Make acceptable for multiple column indexes.
# cols = []
if is_list_like(index):
cols = index # cols.extend(index)
elif index is not None:
cols = [index]
else:
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 this an if/elsif/else

cols = []
cols.append(columns)
Copy link
Contributor

Choose a reason for hiding this comment

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

what happens when columns=None?


append = index is None
indexed = data.set_index(cols, append=append)

else:
if index is None:
Copy link
Contributor

Choose a reason for hiding this comment

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

same here

index = data.index
index = MultiIndex.from_arrays([data.index, data[columns]])
elif is_list_like(index):
Copy link
Member

Choose a reason for hiding this comment

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

I think it would help readability if the conditions here were refactored to be in the same sequence as the conditions in the branch above, as IIUC we essentially evaluate the same conditions in both branches

# Iterating through the list of multiple columns of an index.
indexes = [data[column] for column in index]
indexes.append(data[columns])
Copy link
Member

Choose a reason for hiding this comment

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

What does this do?

index = MultiIndex.from_arrays(indexes)
Copy link
Contributor

Choose a reason for hiding this comment

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

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.

I don't think so but let me know if I should.

else:
# Build multi-indexes if index is not None and not a list.
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 this an if/elseif/else

Copy link
Contributor Author

Choose a reason for hiding this comment

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

I am not sure about the last if/else statement. I can pull if/elif/else for the first three but I still need to have another condition for the last two.

Copy link
Contributor

Choose a reason for hiding this comment

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

these are comments are not very useful, you are just repeating the code, can you make more informative

index = data[index]
index = MultiIndex.from_arrays([index, data[columns]])
Copy link
Member

Choose a reason for hiding this comment

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

Can't you construct "the first draft" of index and then call index = index = MultiIndex.from_arrays([index, data[columns]]) outside of the if-else block?

index = MultiIndex.from_arrays([index, data[columns]])

if is_list_like(values) and not isinstance(values, tuple):
# Exclude tuple because it is seen as a single column name
# Exclude tuple because it is seen as a single column name.
indexed = data._constructor(data[values].values, index=index,
columns=values)
else:
Expand Down
27 changes: 27 additions & 0 deletions pandas/tests/reshape/test_pivot.py
Original file line number Diff line number Diff line change
Expand Up @@ -301,6 +301,33 @@ def test_pivot_multi_functions(self):
expected = concat([means, stds], keys=['mean', 'std'], axis=1)
tm.assert_frame_equal(result, expected)

@pytest.mark.parametrize('method', [True, False])
def test_pivot_multiple_columns_as_index(self, method):
# adding the test case for multiple columns as index (#21425)
df = DataFrame({'lev1': [1, 1, 1, 1, 2, 2, 2, 2],
'lev2': [1, 1, 2, 2, 1, 1, 2, 2],
'lev3': [1, 2, 1, 2, 1, 2, 1, 2],
'values': [0, 1, 2, 3, 4, 5, 6, 7]})
data = [[0, 1], [2, 3], [4, 5], [6, 7]]
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 do the test caess 1 after the other and use the standard

result=
expected=
assert_frame_equal(result, expected)

exp_index = pd.MultiIndex.from_product([[1, 2], [1, 2]],
names=['lev1', 'lev2'])
if method:
result = df.pivot(index=['lev1', 'lev2'],
columns='lev3',
values='values')
exp_columns = Index([1, 2], name='lev3')

else:
result = df.pivot(index=['lev1', 'lev2'],
columns='lev3')
exp_columns = MultiIndex(levels=[['values'], [1, 2]],
Copy link
Member

Choose a reason for hiding this comment

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

Can you use one of the more idiomatic MultiIndex.from_ constructors here instead? Would help readability

codes=[[0, 0], [0, 1]],
names=[None, 'lev3'])

expected = DataFrame(data=data, index=exp_index,
Copy link
Contributor

Choose a reason for hiding this comment

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

is there a test for columns=None and list-like index?

columns=exp_columns)
tm.assert_frame_equal(result, expected)

@pytest.mark.parametrize('method', [True, False])
def test_pivot_index_with_nan(self, method):
# GH 3588
Expand Down