Skip to content

Commit 1708e90

Browse files
authored
ENH: Enable .mode to sort with NA values (pandas-dev#60702)
1 parent 221ad46 commit 1708e90

File tree

3 files changed

+6
-26
lines changed

3 files changed

+6
-26
lines changed

pandas/core/algorithms.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -1012,7 +1012,7 @@ def mode(
10121012
return npresult, res_mask # type: ignore[return-value]
10131013

10141014
try:
1015-
npresult = np.sort(npresult)
1015+
npresult = safe_sort(npresult)
10161016
except TypeError as err:
10171017
warnings.warn(
10181018
f"Unable to sort modes: {err}",

pandas/tests/frame/test_reductions.py

+2-15
Original file line numberDiff line numberDiff line change
@@ -672,23 +672,10 @@ def test_mode_dropna(self, dropna, expected):
672672
expected = DataFrame(expected)
673673
tm.assert_frame_equal(result, expected)
674674

675-
def test_mode_sortwarning(self, using_infer_string):
676-
# Check for the warning that is raised when the mode
677-
# results cannot be sorted
678-
675+
def test_mode_sort_with_na(self, using_infer_string):
679676
df = DataFrame({"A": [np.nan, np.nan, "a", "a"]})
680677
expected = DataFrame({"A": ["a", np.nan]})
681-
682-
# TODO(infer_string) avoid this UserWarning for python storage
683-
warning = (
684-
None
685-
if using_infer_string and df.A.dtype.storage == "pyarrow"
686-
else UserWarning
687-
)
688-
with tm.assert_produces_warning(warning, match="Unable to sort modes"):
689-
result = df.mode(dropna=False)
690-
result = result.sort_values(by="A").reset_index(drop=True)
691-
678+
result = df.mode(dropna=False)
692679
tm.assert_frame_equal(result, expected)
693680

694681
def test_mode_empty_df(self):

pandas/tests/reductions/test_reductions.py

+3-10
Original file line numberDiff line numberDiff line change
@@ -1607,17 +1607,10 @@ def test_mode_intoverflow(self, dropna, expected1, expected2):
16071607
expected2 = Series(expected2, dtype=np.uint64)
16081608
tm.assert_series_equal(result, expected2)
16091609

1610-
def test_mode_sortwarning(self):
1611-
# Check for the warning that is raised when the mode
1612-
# results cannot be sorted
1613-
1614-
expected = Series(["foo", np.nan], dtype=object)
1610+
def test_mode_sort_with_na(self):
16151611
s = Series([1, "foo", "foo", np.nan, np.nan])
1616-
1617-
with tm.assert_produces_warning(UserWarning, match="Unable to sort modes"):
1618-
result = s.mode(dropna=False)
1619-
result = result.sort_values().reset_index(drop=True)
1620-
1612+
expected = Series(["foo", np.nan], dtype=object)
1613+
result = s.mode(dropna=False)
16211614
tm.assert_series_equal(result, expected)
16221615

16231616
def test_mode_boolean_with_na(self):

0 commit comments

Comments
 (0)