Skip to content

Commit 53b1638

Browse files
rhshadrachjorisvandenbossche
authored andcommitted
ENH: Enable .mode to sort with NA values (pandas-dev#60702)
(cherry picked from commit 1708e90)
1 parent 36d34a1 commit 53b1638

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
@@ -1053,7 +1053,7 @@ def mode(
10531053
return npresult, res_mask # type: ignore[return-value]
10541054

10551055
try:
1056-
npresult = np.sort(npresult)
1056+
npresult = safe_sort(npresult)
10571057
except TypeError as err:
10581058
warnings.warn(
10591059
f"Unable to sort modes: {err}",

pandas/tests/frame/test_reductions.py

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

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

696683
def test_mode_empty_df(self):

pandas/tests/reductions/test_reductions.py

+3-10
Original file line numberDiff line numberDiff line change
@@ -1661,17 +1661,10 @@ def test_mode_intoverflow(self, dropna, expected1, expected2):
16611661
expected2 = Series(expected2, dtype=np.uint64)
16621662
tm.assert_series_equal(result, expected2)
16631663

1664-
def test_mode_sortwarning(self):
1665-
# Check for the warning that is raised when the mode
1666-
# results cannot be sorted
1667-
1668-
expected = Series(["foo", np.nan], dtype=object)
1664+
def test_mode_sort_with_na(self):
16691665
s = Series([1, "foo", "foo", np.nan, np.nan])
1670-
1671-
with tm.assert_produces_warning(UserWarning):
1672-
result = s.mode(dropna=False)
1673-
result = result.sort_values().reset_index(drop=True)
1674-
1666+
expected = Series(["foo", np.nan], dtype=object)
1667+
result = s.mode(dropna=False)
16751668
tm.assert_series_equal(result, expected)
16761669

16771670
def test_mode_boolean_with_na(self):

0 commit comments

Comments
 (0)