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

BUG: pivot_table not returning correct type when margin=True and aggfunc='mean' #28248

Merged
merged 15 commits into from
Nov 23, 2019
Merged
Show file tree
Hide file tree
Changes from 10 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/v1.0.0.rst
Original file line number Diff line number Diff line change
Expand Up @@ -186,6 +186,7 @@ Reshaping

-
-
- Bug in :meth:`pivot_table` not returning correct type ``float`` when ``margins=True`` and ``aggfunc='mean'`` (:issue:`24893`)

Sparse
^^^^^^
Expand Down
5 changes: 4 additions & 1 deletion pandas/core/reshape/pivot.py
Original file line number Diff line number Diff line change
Expand Up @@ -252,9 +252,12 @@ def _add_margins(

row_names = result.index.names
try:
mabelvj marked this conversation as resolved.
Show resolved Hide resolved
# check the result column and leave floats
for dtype in set(result.dtypes):
cols = result.select_dtypes([dtype]).columns
margin_dummy[cols] = margin_dummy[cols].astype(dtype)
margin_dummy[cols] = margin_dummy[cols].apply(
maybe_downcast_to_dtype, args=(dtype,)
)
result = result.append(margin_dummy)
except TypeError:

Expand Down
Empty file.
19 changes: 19 additions & 0 deletions pandas/tests/reshape/test_pivot.py
Original file line number Diff line number Diff line change
Expand Up @@ -1630,6 +1630,25 @@ def test_categorical_margins_category(self, observed):
table = df.pivot_table("x", "y", "z", dropna=observed, margins=True)
tm.assert_frame_equal(table, expected)

def test_margins_casted_to_float(self, observed):
# GH #24893
df = pd.DataFrame(
{
"A": [2, 4, 6, 8],
"B": [1, 4, 5, 8],
"C": [1, 3, 4, 6],
"D": ["X", "X", "Y", "Y"],
}
)

result = pd.pivot_table(df, index="D", margins=True)
expected = pd.DataFrame(
{"A": [3, 7, 5], "B": [2.5, 6.5, 4.5], "C": [2, 5, 3.5]},
index=pd.Index(["X", "Y", "All"], name="D"),
)
table = result
mabelvj marked this conversation as resolved.
Show resolved Hide resolved
tm.assert_frame_equal(result, expected)

def test_categorical_aggfunc(self, observed):
# GH 9534
df = pd.DataFrame(
Expand Down