Skip to content

Commit 2cec983

Browse files
committed
BUG: Aggregation on arrow array return same type.
Signed-off-by: Liang Yan <[email protected]>
1 parent 406abd9 commit 2cec983

File tree

2 files changed

+35
-2
lines changed

2 files changed

+35
-2
lines changed

pandas/core/dtypes/cast.py

+12-2
Original file line numberDiff line numberDiff line change
@@ -461,7 +461,7 @@ def maybe_cast_pointwise_result(
461461
"""
462462

463463
if isinstance(dtype, ExtensionDtype):
464-
if not isinstance(dtype, (CategoricalDtype, DatetimeTZDtype)):
464+
if not isinstance(dtype, (CategoricalDtype, DatetimeTZDtype, ArrowDtype)):
465465
# TODO: avoid this special-casing
466466
# We have to special case categorical so as not to upcast
467467
# things like counts back to categorical
@@ -471,7 +471,17 @@ def maybe_cast_pointwise_result(
471471
result = _maybe_cast_to_extension_array(cls, result, dtype=dtype)
472472
else:
473473
result = _maybe_cast_to_extension_array(cls, result)
474-
474+
elif isinstance(dtype, ArrowDtype):
475+
pyarrow_type = convert_dtypes(result, dtype_backend="pyarrow")
476+
if isinstance(pyarrow_type, ExtensionDtype):
477+
cls = pyarrow_type.construct_array_type()
478+
result = _maybe_cast_to_extension_array(cls, result)
479+
else:
480+
cls = dtype.construct_array_type()
481+
if same_dtype:
482+
result = _maybe_cast_to_extension_array(cls, result, dtype=dtype)
483+
else:
484+
result = _maybe_cast_to_extension_array(cls, result)
475485
elif (numeric_only and dtype.kind in "iufcb") or not numeric_only:
476486
result = maybe_downcast_to_dtype(result, dtype)
477487

pandas/tests/groupby/aggregate/test_aggregate.py

+23
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@
55
import functools
66
from functools import partial
77
import re
8+
import typing
89

910
import numpy as np
1011
import pytest
@@ -1607,3 +1608,25 @@ def test_agg_with_as_index_false_with_list():
16071608
columns=MultiIndex.from_tuples([("a1", ""), ("a2", ""), ("b", "sum")]),
16081609
)
16091610
tm.assert_frame_equal(result, expected)
1611+
1612+
1613+
@pytest.mark.skipif(
1614+
not typing.TYPE_CHECKING, reason="let pyarrow to be imported in dtypes.py"
1615+
)
1616+
def test_agg_arrow_type():
1617+
df = DataFrame.from_dict(
1618+
{
1619+
"category": ["A"] * 10 + ["B"] * 10,
1620+
"bool_numpy": [True] * 5 + [False] * 5 + [True] * 5 + [False] * 5,
1621+
}
1622+
)
1623+
df["bool_arrow"] = df["bool_numpy"].astype("bool[pyarrow]")
1624+
result = df.groupby("category").agg(lambda x: x.sum() / x.count())
1625+
expected = DataFrame(
1626+
{
1627+
"bool_numpy": [0.5, 0.5],
1628+
"bool_arrow": Series([0.5, 0.5]).astype("double[pyarrow]").values,
1629+
},
1630+
index=Index(["A", "B"], name="category"),
1631+
)
1632+
tm.assert_frame_equal(result, expected)

0 commit comments

Comments
 (0)