Skip to content

BUG: pivot_table with overlapping values #61293

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

Open
wants to merge 17 commits into
base: main
Choose a base branch
from
Open
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
1 change: 1 addition & 0 deletions doc/source/whatsnew/v3.0.0.rst
Original file line number Diff line number Diff line change
Expand Up @@ -806,6 +806,7 @@ Reshaping
- Bug in :meth:`DataFrame.unstack` producing incorrect results when ``sort=False`` (:issue:`54987`, :issue:`55516`)
- Bug in :meth:`DataFrame.merge` when merging two :class:`DataFrame` on ``intc`` or ``uintc`` types on Windows (:issue:`60091`, :issue:`58713`)
- Bug in :meth:`DataFrame.pivot_table` incorrectly subaggregating results when called without an ``index`` argument (:issue:`58722`)
- Bug in :meth:`DataFrame.pivot_table` incorrectly ignoring the ``values`` argument when also supplied to the ``index`` or ``columns`` parameters (:issue:`57876`, :issue:`61292`)
- Bug in :meth:`DataFrame.stack` with the new implementation where ``ValueError`` is raised when ``level=[]`` (:issue:`60740`)
- Bug in :meth:`DataFrame.unstack` producing incorrect results when manipulating empty :class:`DataFrame` with an :class:`ExtentionDtype` (:issue:`59123`)
- Bug in :meth:`concat` where concatenating DataFrame and Series with ``ignore_index = True`` drops the series name (:issue:`60723`, :issue:`56257`)
Expand Down
5 changes: 5 additions & 0 deletions pandas/core/reshape/pivot.py
Original file line number Diff line number Diff line change
Expand Up @@ -336,6 +336,11 @@ def __internal_pivot_table(
values = list(values)

grouped = data.groupby(keys, observed=observed, sort=sort, dropna=dropna)
if values_passed:
# GH#57876 and GH#61292
# mypy is not aware `grouped[values]` will always be a DataFrameGroupBy
grouped = grouped[values] # type: ignore[assignment]

agged = grouped.agg(aggfunc, **kwargs)

if dropna and isinstance(agged, ABCDataFrame) and len(agged.columns):
Expand Down
33 changes: 33 additions & 0 deletions pandas/tests/reshape/test_pivot.py
Original file line number Diff line number Diff line change
Expand Up @@ -2554,6 +2554,39 @@ def test_pivot_table_index_and_column_keys_with_nan(self, dropna):

tm.assert_frame_equal(left=result, right=expected)

@pytest.mark.parametrize(
"index, columns",
[("Category", "Value"), ("Value", "Category")],
ids=["values-and-columns", "values-and-index"],
)
def test_pivot_table_values_as_two_params(self, index, columns, request):
# GH#57876
data = {"Category": ["A", "B", "A", "B"], "Value": [10, 20, 40, 50]}
df = DataFrame(data)
result = df.pivot_table(
index=index, columns=columns, values="Value", aggfunc="count"
)
nan = np.nan
cat_index = Index(data=["A", "B"], name="Category")
val_index = Index(data=[10, 20, 40, 50], name="Value")
if request.node.callspec.id == "values-and-columns":
e_data = [
[1.0, nan, 1.0, nan],
[nan, 1.0, nan, 1.0],
]
expected = DataFrame(data=e_data, index=cat_index, columns=val_index)

else:
e_data = [
[1.0, nan],
[nan, 1.0],
[1.0, nan],
[nan, 1.0],
]
expected = DataFrame(data=e_data, index=val_index, columns=cat_index)

tm.assert_frame_equal(result, expected)


class TestPivot:
def test_pivot(self):
Expand Down
42 changes: 42 additions & 0 deletions pandas/tests/reshape/test_pivot_multilevel.py
Original file line number Diff line number Diff line change
Expand Up @@ -250,3 +250,45 @@ def test_pivot_df_multiindex_index_none():
columns=Index(["label1", "label2"], name="label"),
)
tm.assert_frame_equal(result, expected)


@pytest.mark.parametrize(
"index, columns",
[("index", ["col", "value"]), (["index", "value"], "col")],
ids=["values-and-columns", "values-and-index"],
)
def test_pivot_table_multiindex_values_as_two_params(index, columns, request):
# GH#61292
data = [
["A", 1, 50, -1],
["B", 1, 100, -2],
["A", 2, 100, -2],
["B", 2, 200, -4],
]
df = pd.DataFrame(data=data, columns=["index", "col", "value", "extra"])
result = df.pivot_table(values="value", index=index, columns=columns)
nan = np.nan
if request.node.callspec.id == "values-and-columns":
e_data = [
[50.0, nan, 100.0, nan],
[nan, 100.0, nan, 200.0],
]
e_index = Index(data=["A", "B"], name="index")
e_cols = MultiIndex.from_arrays(
arrays=[[1, 1, 2, 2], [50, 100, 100, 200]], names=["col", "value"]
)

else:
e_data = [
[50.0, nan],
[nan, 100.0],
[100.0, nan],
[nan, 200.0],
]
e_index = MultiIndex.from_arrays(
arrays=[["A", "A", "B", "B"], [50, 100, 100, 200]], names=["index", "value"]
)
e_cols = Index(data=[1, 2], name="col")

expected = pd.DataFrame(data=e_data, index=e_index, columns=e_cols)
tm.assert_frame_equal(result, expected)
Loading