Skip to content

BUG: GroupBy return EA dtype #23318

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

Merged
merged 15 commits into from
Nov 6, 2018
Merged
Show file tree
Hide file tree
Changes from 3 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
13 changes: 13 additions & 0 deletions pandas/core/groupby/groupby.py
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ class providing the base-class of operations.

from pandas.core.dtypes.common import (
is_numeric_dtype,
is_extension_array_dtype,
is_scalar,
ensure_float)
from pandas.core.dtypes.cast import maybe_downcast_to_dtype
Expand Down Expand Up @@ -758,6 +759,18 @@ def _try_cast(self, result, obj, numeric_only=False):
else:
dtype = obj.dtype

if is_extension_array_dtype(dtype):
# The function can return something of any type, so check
# if the type is compatible with the calling EA.
try:
result = obj.values._from_sequence(result)
except Exception:
# https://github.com/pandas-dev/pandas/issues/22850
# pandas has no control over what 3rd-party ExtensionArrays
# do in _values_from_sequence. We still want ops to work
# though, so we catch any regular Exception.
pass

if not is_scalar(result):
if numeric_only and is_numeric_dtype(dtype) or not numeric_only:
result = maybe_downcast_to_dtype(result, dtype)
Expand Down
10 changes: 10 additions & 0 deletions pandas/tests/groupby/test_grouping.py
Original file line number Diff line number Diff line change
Expand Up @@ -282,6 +282,16 @@ def test_groupby_categorical_index_and_columns(self, observed):
expected = DataFrame(data=expected_data.T, index=expected_columns)
assert_frame_equal(result, expected)

def test_groupby_extension_array(self):

# GH23227
# groupby on an extension array should return the extension array type
df = pd.DataFrame({'Int': pd.Series([1, 2, 3], dtype='Int64'),
'A': [1, 2, 1]})
result = df.groupby('A').Int.sum()
assert result is not None
assert result.dtype.name == 'Int64'

def test_grouper_getting_correct_binner(self):

# GH 10063
Expand Down