Skip to content

Commit 2450800

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

File tree

2 files changed

+34
-2
lines changed

2 files changed

+34
-2
lines changed

pandas/core/dtypes/cast.py

+12-2
Original file line numberDiff line numberDiff line change
@@ -458,7 +458,7 @@ def maybe_cast_pointwise_result(
458458
"""
459459

460460
if isinstance(dtype, ExtensionDtype):
461-
if not isinstance(dtype, (CategoricalDtype, DatetimeTZDtype)):
461+
if not isinstance(dtype, (CategoricalDtype, DatetimeTZDtype, ArrowDtype)):
462462
# TODO: avoid this special-casing
463463
# We have to special case categorical so as not to upcast
464464
# things like counts back to categorical
@@ -468,7 +468,17 @@ def maybe_cast_pointwise_result(
468468
result = _maybe_cast_to_extension_array(cls, result, dtype=dtype)
469469
else:
470470
result = _maybe_cast_to_extension_array(cls, result)
471-
471+
elif isinstance(dtype, ArrowDtype):
472+
pyarrow_type = convert_dtypes(result, dtype_backend="pyarrow")
473+
if isinstance(pyarrow_type, ExtensionDtype):
474+
cls = pyarrow_type.construct_array_type()
475+
result = _maybe_cast_to_extension_array(cls, result)
476+
else:
477+
cls = dtype.construct_array_type()
478+
if same_dtype:
479+
result = _maybe_cast_to_extension_array(cls, result, dtype=dtype)
480+
else:
481+
result = _maybe_cast_to_extension_array(cls, result)
472482
elif (numeric_only and dtype.kind in "iufcb") or not numeric_only:
473483
result = maybe_downcast_to_dtype(result, dtype)
474484

pandas/tests/groupby/aggregate/test_aggregate.py

+22
Original file line numberDiff line numberDiff line change
@@ -1603,3 +1603,25 @@ def test_agg_with_as_index_false_with_list():
16031603
columns=MultiIndex.from_tuples([("a1", ""), ("a2", ""), ("b", "sum")]),
16041604
)
16051605
tm.assert_frame_equal(result, expected)
1606+
1607+
1608+
# @pytest.mark.skipif(
1609+
# not typing.TYPE_CHECKING, reason="TYPE_CHECKING must be True to import pyarrow"
1610+
# )
1611+
def test_agg_arrow_type():
1612+
df = DataFrame.from_dict(
1613+
{
1614+
"category": ["A"] * 10 + ["B"] * 10,
1615+
"bool_numpy": [True] * 5 + [False] * 5 + [True] * 5 + [False] * 5,
1616+
}
1617+
)
1618+
df["bool_arrow"] = df["bool_numpy"].astype("bool[pyarrow]")
1619+
result = df.groupby("category").agg(lambda x: x.sum() / x.count())
1620+
expected = DataFrame(
1621+
{
1622+
"bool_numpy": [0.5, 0.5],
1623+
"bool_arrow": Series([0.5, 0.5]).astype("double[pyarrow]").values,
1624+
},
1625+
index=Index(["A", "B"], name="category"),
1626+
)
1627+
tm.assert_frame_equal(result, expected)

0 commit comments

Comments
 (0)