-
-
Notifications
You must be signed in to change notification settings - Fork 18.4k
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
Conversation
Codecov Report
@@ Coverage Diff @@
## master #25330 +/- ##
===========================================
- Coverage 91.72% 41.71% -50.01%
===========================================
Files 173 173
Lines 52831 52841 +10
===========================================
- Hits 48457 22045 -26412
- Misses 4374 30796 +26422
Continue to review full report at Codecov.
|
Codecov Report
@@ Coverage Diff @@
## master #25330 +/- ##
==========================================
+ Coverage 91.27% 91.27% +<.01%
==========================================
Files 173 173
Lines 53002 53011 +9
==========================================
+ Hits 48375 48384 +9
Misses 4627 4627
Continue to review full report at Codecov.
|
else: | ||
index = data[index] | ||
index = MultiIndex.from_arrays([index, data[columns]]) |
There was a problem hiding this comment.
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?
pandas/core/reshape/pivot.py
Outdated
@@ -368,15 +368,29 @@ def _convert_by(by): | |||
@Appender(_shared_docs['pivot'], indents=1) | |||
def pivot(data, index=None, columns=None, values=None): | |||
if values is None: | |||
cols = [columns] if index is None else [index, columns] | |||
if index is None: |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
can you add comments here delineating the cases
append = index is None | ||
indexed = data.set_index(cols, append=append) | ||
|
||
else: | ||
if index is None: |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
same here
pandas/core/reshape/pivot.py
Outdated
else: | ||
if index is None: | ||
index = data.index | ||
index = MultiIndex.from_arrays([index, data[columns]]) |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
do you need to pass names?
# Iterating through the list of multiple columns of an index | ||
indexes = [data[column] for column in index] | ||
indexes.append(data[columns]) | ||
index = MultiIndex.from_arrays(indexes) |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
names?
There was a problem hiding this comment.
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.
values='values') | ||
result_no_values = df.pivot(index=['lev1', 'lev2'], | ||
columns='lev3') | ||
data = [[0, 1], [2, 3], [4, 5], [6, 7]] |
There was a problem hiding this comment.
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)
cols = [columns] if index is None else [index, columns] | ||
if index is None: | ||
cols = [columns] | ||
else: |
There was a problem hiding this comment.
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
else: | ||
# Build multi-indexes if index is not None and not a list. |
There was a problem hiding this comment.
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
There was a problem hiding this comment.
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.
else: | ||
# Build multi-indexes if index is not None and not a list. |
There was a problem hiding this comment.
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
pandas/core/reshape/pivot.py
Outdated
cols = [columns] | ||
else: | ||
if is_list_like(index): | ||
# If a given index is a list, set cols to index. |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
similar to below can you make more informative comments
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Any suggestion ? I am still new to these. Thanks.
* upstream/master: BUG: Fix passing of numeric_only argument for categorical reduce (pandas-dev#25304) ENH: Support times with timezones in at_time (pandas-dev#25280) COMPAT: alias .to_numpy() for timestamp and timedelta scalars (pandas-dev#25142) DOC/CLN: Fix various docstring errors (pandas-dev#25295) Bug: OverflowError in resample.agg with tz data (pandas-dev#25297) Fixes Formatting Exception (pandas-dev#25088) BUG: groupby.transform retains timezone information (pandas-dev#25264) Doc: corrects spelling in generic.py (pandas-dev#25333) Fix typos in docs (pandas-dev#25305)
* upstream/master: TST: use a fixed seed to have the same uniques across python versions (pandas-dev#25346)
* upstream/master: TST: xfail excel styler tests, xref GH25351 (pandas-dev#25352)
pandas/core/reshape/pivot.py
Outdated
# Make acceptable for multiple column indexes. | ||
cols = [] | ||
if is_list_like(index): | ||
cols.extend(index) |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
the if/elif/else was fine here; don't create then extend, just create in each block
can you merge master and update to comments |
* upstream/master: (110 commits) DOC: hardcode contributors for 0.24.x releases (pandas-dev#25662) DOC: restore toctree maxdepth (pandas-dev#25134) BUG: Redefine IndexOpsMixin.size, fix pandas-dev#25580. (pandas-dev#25584) BUG: to_csv line endings with compression (pandas-dev#25625) DOC: file obj for to_csv must be newline='' (pandas-dev#25624) Suppress incorrect warning in nargsort for timezone-aware DatetimeIndex (pandas-dev#25629) TST: fix incorrect sparse test (now failing on scipy master) (pandas-dev#25653) CLN: Removed debugging code (pandas-dev#25647) DOC: require Return section only if return is not None nor commentary (pandas-dev#25008) DOC:Remove hard-coded examples from _flex_doc_SERIES (pandas-dev#24589) (pandas-dev#25524) TST: xref pandas-dev#25630 (pandas-dev#25643) BUG: Fix pandas-dev#25481 by fixing the error message in TypeError (pandas-dev#25540) Fixturize tests/frame/test_mutate_columns.py (pandas-dev#25642) Fixturize tests/frame/test_join.py (pandas-dev#25639) Fixturize tests/frame/test_combine_concat.py (pandas-dev#25634) Fixturize tests/frame/test_asof.py (pandas-dev#25628) BUG: Fix user-facing AssertionError with to_html (pandas-dev#25608) (pandas-dev#25620) DOC: resolve all GL03 docstring validation errors (pandas-dev#25525) TST: failing wheel building on PY2 and old numpy (pandas-dev#25631) DOC: Remove makePanel from docs (pandas-dev#25609) (pandas-dev#25612) ...
can you merge master |
* upstream/master: (55 commits) PERF: Improve performance of StataReader (pandas-dev#25780) Speed up tokenizing of a row in csv and xstrtod parsing (pandas-dev#25784) BUG: Fix _binop for operators for serials which has more than one returns (divmod/rdivmod). (pandas-dev#25588) BUG-24971 copying blocks also considers ndim (pandas-dev#25521) CLN: Panel reference from documentation (pandas-dev#25649) ENH: Quoting column names containing spaces with backticks to use them in query and eval. (pandas-dev#24955) BUG: reading windows utf8 filenames in py3.6 (pandas-dev#25769) DOC: clean bug fix section in whatsnew (pandas-dev#25792) DOC: Fixed PeriodArray api ref (pandas-dev#25526) Move locale code out of tm, into _config (pandas-dev#25757) Unpin pycodestyle (pandas-dev#25789) Add test for rdivmod on EA array (GH23287) (pandas-dev#24047) ENH: Support datetime.timezone objects (pandas-dev#25065) Cython language level 3 (pandas-dev#24538) API: concat on sparse values (pandas-dev#25719) TST: assert_produces_warning works with filterwarnings (pandas-dev#25721) make core.config self-contained (pandas-dev#25613) CLN: replace %s syntax with .format in pandas.io.parsers (pandas-dev#24721) TST: Check pytables<3.5.1 when skipping (pandas-dev#25773) DOC: Fix typo in docstring of DataFrame.memory_usage (pandas-dev#25770) ...
Closing this one as stale. Let us know if you'd like to pick it back up @thoo ! |
Sorry reopening this as I think it went stale on the review side. Will try to take a look and give feedback the next few days |
else: | ||
result = df.pivot(index=['lev1', 'lev2'], | ||
columns='lev3') | ||
exp_columns = MultiIndex(levels=[['values'], [1, 2]], |
There was a problem hiding this comment.
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
else: | ||
if index is None: | ||
index = data.index | ||
index = MultiIndex.from_arrays([data.index, data[columns]]) | ||
elif is_list_like(index): |
There was a problem hiding this comment.
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
elif is_list_like(index): | ||
# Iterating through the list of multiple columns of an index. | ||
indexes = [data[column] for column in index] | ||
indexes.append(data[columns]) |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
What does this do?
@@ -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. |
There was a problem hiding this comment.
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.
@@ -368,18 +368,34 @@ def _convert_by(by): | |||
@Appender(_shared_docs['pivot'], indents=1) |
There was a problem hiding this comment.
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
cols = [index] | ||
else: | ||
cols = [] | ||
cols.append(columns) |
There was a problem hiding this comment.
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?
codes=[[0, 0], [0, 1]], | ||
names=[None, 'lev3']) | ||
|
||
expected = DataFrame(data=data, index=exp_index, |
There was a problem hiding this comment.
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?
can you merge master and update to comments |
can you merge master |
closing as stale, but pretty close if you'd like to finish up. |
git diff upstream/master -u -- "*.py" | flake8 --diff