Skip to content

Commit 4700e77

Browse files
committed
BUG: transform with nunique should have dtype int64
GH35109
1 parent 7453810 commit 4700e77

File tree

3 files changed

+11
-0
lines changed

3 files changed

+11
-0
lines changed

doc/source/whatsnew/v1.1.0.rst

+1
Original file line numberDiff line numberDiff line change
@@ -1080,6 +1080,7 @@ Groupby/resample/rolling
10801080
- Bug in :meth:`DataFrame.groupby` lost index, when one of the ``agg`` keys referenced an empty list (:issue:`32580`)
10811081
- Bug in :meth:`Rolling.apply` where ``center=True`` was ignored when ``engine='numba'`` was specified (:issue:`34784`)
10821082
- Bug in :meth:`DataFrame.ewm.cov` was throwing ``AssertionError`` for :class:`MultiIndex` inputs (:issue:`34440`)
1083+
- Bug in :meth:`core.groupby.DataFrameGroupBy.transform` when ``func='nunique'`` and columns are of type ``datetime64``, the result would also be of type ``datetime64`` instead of ``int64`` (:issue:`35109`)
10831084

10841085
Reshaping
10851086
^^^^^^^^^

pandas/core/dtypes/cast.py

+3
Original file line numberDiff line numberDiff line change
@@ -319,6 +319,9 @@ def maybe_cast_result_dtype(dtype: DtypeObj, how: str) -> DtypeObj:
319319
return np.dtype(np.int64)
320320
elif how in ["add", "cumsum", "sum"] and isinstance(dtype, BooleanDtype):
321321
return Int64Dtype()
322+
elif how == "nunique":
323+
return np.dtype(np.int64)
324+
322325
return dtype
323326

324327

pandas/tests/groupby/test_nunique.py

+7
Original file line numberDiff line numberDiff line change
@@ -167,3 +167,10 @@ def test_nunique_preserves_column_level_names():
167167
result = test.groupby([0, 0, 0]).nunique()
168168
expected = pd.DataFrame([2], columns=test.columns)
169169
tm.assert_frame_equal(result, expected)
170+
171+
172+
def test_nunique_transform_with_datetime():
173+
df = pd.DataFrame(date_range("2008-12-31", "2009-01-02"), columns=["date"])
174+
result = df.groupby([0, 0, 1])["date"].transform("nunique")
175+
expected = pd.Series([2, 2, 1], name="date")
176+
tm.assert_series_equal(result, expected)

0 commit comments

Comments
 (0)