Skip to content
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

BUG : fix Series.mode throwing exception with dropna=False and no nul… #58931

Closed
wants to merge 2 commits into from
Closed
Changes from all 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
1 change: 1 addition & 0 deletions doc/source/whatsnew/v3.0.0.rst
Original file line number Diff line number Diff line change
@@ -572,6 +572,7 @@ Other
- 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`)
- 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`)
- Bug in :meth:`Series.diff` allowing non-integer values for the ``periods`` argument. (:issue:`56607`)
- 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`)
- Bug in :meth:`Series.rank` that doesn't preserve missing values for nullable integers when ``na_option='keep'``. (:issue:`56976`)
- Bug in :meth:`Series.replace` and :meth:`DataFrame.replace` inconsistently replacing matching instances when ``regex=True`` and missing values are present. (:issue:`56599`)
- Bug in Dataframe Interchange Protocol implementation was returning incorrect results for data buffers' associated dtype, for string and datetime columns (:issue:`54781`)
2 changes: 1 addition & 1 deletion pandas/_libs/hashtable_func_helper.pxi.in
Original file line number Diff line number Diff line change
@@ -443,7 +443,7 @@ def mode(ndarray[htfunc_t] values, bint dropna, const uint8_t[:] mask=None):

if na_counter > 0:
res_mask = np.zeros(j+1, dtype=np.bool_)
res_mask[j] = True
res_mask[j] = (na_counter == max_count)
return modes[:j + 1], res_mask


8 changes: 7 additions & 1 deletion pandas/core/arrays/masked.py
Original file line number Diff line number Diff line change
@@ -1093,7 +1093,13 @@ def _mode(self, dropna: bool = True) -> Self:
result = mode(self._data, dropna=dropna, mask=self._mask)
res_mask = np.zeros(result.shape, dtype=np.bool_)
else:
result, res_mask = mode(self._data, dropna=dropna, mask=self._mask)
res_tuple = mode(self._data, dropna=dropna, mask=self._mask)
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Is it possible to make the return type of mode consistent throughout the code base so we don't have a check like this?

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I did a little investigation earlier and res_mask seems to be incorrect here if the series has pd.NA in it.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

With the mode return type consistency, it's called in a bunch of other places using the return with no mask, so not sure if it's worth changing it to then have to uglify other usages to result, _ = mode(...), return mode(...)[0]

Copy link
Member

@Aloqeely Aloqeely Jun 19, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I agree it's good to have a consistent return type here. result, _ = mode(...) is not ugly to me.

if len(res_tuple) == 2:
result = res_tuple[0]
res_mask = res_tuple[1]
else:
result = res_tuple
res_mask = np.zeros(result.shape, dtype=np.bool_)
result = type(self)(result, res_mask) # type: ignore[arg-type]
return result[result.argsort()]

18 changes: 18 additions & 0 deletions pandas/tests/series/test_reductions.py
Original file line number Diff line number Diff line change
@@ -51,6 +51,24 @@ def test_mode_nullable_dtype(any_numeric_ea_dtype):
tm.assert_series_equal(result, expected)


def test_mode_nullable_dtype_edge_case(any_numeric_ea_dtype):
# GH##58926
ser = Series([1, 1, 2, 3], dtype=any_numeric_ea_dtype)
result = ser.mode(dropna=False)
expected = Series([1], dtype=any_numeric_ea_dtype)
tm.assert_series_equal(result, expected)

ser2 = Series([1, 1, 2, 3, pd.NA], dtype=any_numeric_ea_dtype)
result = ser2.mode(dropna=False)
expected = Series([1], dtype=any_numeric_ea_dtype)
tm.assert_series_equal(result, expected)

ser3 = Series([1, pd.NA, pd.NA], dtype=any_numeric_ea_dtype)
result = ser3.mode(dropna=False)
expected = Series([pd.NA], dtype=any_numeric_ea_dtype)
tm.assert_series_equal(result, expected)


def test_mode_infer_string():
# GH#56183
pytest.importorskip("pyarrow")
Loading
Oops, something went wrong.