Skip to content

Commit dd81d94

Browse files
committed
BUG : fix Series.mode throwing exception with dropna=False and no nulls present (pandas-dev#58926)
1 parent 9e7abc8 commit dd81d94

File tree

3 files changed

+16
-1
lines changed

3 files changed

+16
-1
lines changed

doc/source/whatsnew/v3.0.0.rst

+1
Original file line numberDiff line numberDiff line change
@@ -572,6 +572,7 @@ Other
572572
- Bug in :meth:`DataFrame.where` where using a non-bool type array in the function would return a ``ValueError`` instead of a ``TypeError`` (:issue:`56330`)
573573
- Bug in :meth:`Index.sort_values` when passing a key function that turns values into tuples, e.g. ``key=natsort.natsort_key``, would raise ``TypeError`` (:issue:`56081`)
574574
- Bug in :meth:`Series.diff` allowing non-integer values for the ``periods`` argument. (:issue:`56607`)
575+
- Bug in :meth:`Series.mode` where an exception was raised when taking the mode with nullable types with no null values in the series. (:issue:`58926`)
575576
- Bug in :meth:`Series.rank` that doesn't preserve missing values for nullable integers when ``na_option='keep'``. (:issue:`56976`)
576577
- Bug in :meth:`Series.replace` and :meth:`DataFrame.replace` inconsistently replacing matching instances when ``regex=True`` and missing values are present. (:issue:`56599`)
577578
- Bug in Dataframe Interchange Protocol implementation was returning incorrect results for data buffers' associated dtype, for string and datetime columns (:issue:`54781`)

pandas/core/arrays/masked.py

+7-1
Original file line numberDiff line numberDiff line change
@@ -1093,7 +1093,13 @@ def _mode(self, dropna: bool = True) -> Self:
10931093
result = mode(self._data, dropna=dropna, mask=self._mask)
10941094
res_mask = np.zeros(result.shape, dtype=np.bool_)
10951095
else:
1096-
result, res_mask = mode(self._data, dropna=dropna, mask=self._mask)
1096+
res_tuple = mode(self._data, dropna=dropna, mask=self._mask)
1097+
if len(res_tuple) == 2:
1098+
result = res_tuple[0]
1099+
res_mask = res_tuple[1]
1100+
else:
1101+
result = res_tuple
1102+
res_mask = np.zeros(result.shape, dtype=np.bool_)
10971103
result = type(self)(result, res_mask) # type: ignore[arg-type]
10981104
return result[result.argsort()]
10991105

pandas/tests/series/test_reductions.py

+8
Original file line numberDiff line numberDiff line change
@@ -51,6 +51,14 @@ def test_mode_nullable_dtype(any_numeric_ea_dtype):
5151
tm.assert_series_equal(result, expected)
5252

5353

54+
def test_mode_nullable_dtype_edge_case(any_numeric_ea_dtype):
55+
# GH##58926
56+
ser = Series([1, 1, 2, 3], dtype=any_numeric_ea_dtype)
57+
result = ser.mode(dropna=False)
58+
expected = Series([1], dtype=any_numeric_ea_dtype)
59+
tm.assert_series_equal(result, expected)
60+
61+
5462
def test_mode_infer_string():
5563
# GH#56183
5664
pytest.importorskip("pyarrow")

0 commit comments

Comments
 (0)