@@ -398,3 +398,40 @@ def test_astype_preserves_name(self, index, dtype):
398
398
assert result .names == index .names
399
399
else :
400
400
assert result .name == index .name
401
+
402
+
403
+ @pytest .mark .parametrize ("na_position" , [None , "middle" ])
404
+ def test_sort_values_invalid_na_position (index_with_missing , na_position ):
405
+
406
+ if type (index_with_missing ) in [DatetimeIndex , PeriodIndex , TimedeltaIndex ]:
407
+ pytest .xfail ("stable descending order sort not implemented" )
408
+ elif type (index_with_missing ) in [CategoricalIndex , MultiIndex ]:
409
+ pytest .xfail ("missing value sorting order not defined for index type" )
410
+
411
+ if na_position not in ["first" , "last" ]:
412
+ with pytest .raises (
413
+ ValueError , match = f"invalid na_position: { na_position } " ,
414
+ ):
415
+ index_with_missing .sort_values (na_position = na_position )
416
+
417
+
418
+ @pytest .mark .parametrize ("na_position" , ["first" , "last" ])
419
+ def test_sort_values_with_missing (index_with_missing , na_position ):
420
+ # GH 35584. Test that sort_values works with missing values,
421
+ # sort non-missing and place missing according to na_position
422
+
423
+ if type (index_with_missing ) in [DatetimeIndex , PeriodIndex , TimedeltaIndex ]:
424
+ pytest .xfail ("stable descending order sort not implemented" )
425
+ elif type (index_with_missing ) in [CategoricalIndex , MultiIndex ]:
426
+ pytest .xfail ("missing value sorting order not defined for index type" )
427
+ missing_count = np .sum (index_with_missing .isna ())
428
+ not_na_vals = index_with_missing [index_with_missing .notna ()].values
429
+ sorted_values = np .sort (not_na_vals )
430
+ if na_position == "first" :
431
+ sorted_values = np .concatenate ([[None ] * missing_count , sorted_values ])
432
+ else :
433
+ sorted_values = np .concatenate ([sorted_values , [None ] * missing_count ])
434
+ expected = type (index_with_missing )(sorted_values )
435
+
436
+ result = index_with_missing .sort_values (na_position = na_position )
437
+ tm .assert_index_equal (result , expected )
0 commit comments