diff --git a/src/xarray_regrid/methods/flox_reduce.py b/src/xarray_regrid/methods/flox_reduce.py index 6045306..f0c37ec 100644 --- a/src/xarray_regrid/methods/flox_reduce.py +++ b/src/xarray_regrid/methods/flox_reduce.py @@ -180,7 +180,12 @@ def compute_mode( expected_groups=(pd.Index(values.astype(data)), *bounds), fill_value=-1, ) - result = result.idxmax(array_name) if not anti_mode else result.idxmin(array_name) + if anti_mode: + # Labels absent from a cell have the fill count (-1): exclude them. + absent = np.iinfo(result.dtype).max + result = result.where(result > 0, absent).idxmin(array_name) + else: + result = result.idxmax(array_name) result = restore_properties(result, data, target_ds, coords, fill_value) result = result.reindex_like(target_coords, copy=False) diff --git a/tests/test_reduce.py b/tests/test_reduce.py index fbc7a21..fa52115 100644 --- a/tests/test_reduce.py +++ b/tests/test_reduce.py @@ -111,11 +111,30 @@ def test_most_common(dummy_lc_data, dummy_target_grid): def test_least_common(dummy_lc_data, dummy_target_grid): - # Currently just test if the method runs: code is 99% the same as most_common - dummy_lc_data["lc"].regrid.least_common( + # Labels absent from a cell must not be selected. + expected_data = np.array( + [ + [2, 2, 0, 0, 0, 0], + [0, 2, 2, 0, 0, 0], + [0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0], + [3, 0, 0, 0, 0, 1], + ], + dtype="uint8", + ) + input_data_int = dummy_lc_data["lc"].astype("uint8") + + regrid_result = input_data_int.regrid.least_common( dummy_target_grid, values=EXP_LABELS, ) + xr.testing.assert_equal( + regrid_result, + make_expected_ds(expected_data)["lc"], + ) + + assert regrid_result.dtype == input_data_int.dtype def test_oversized_most_common(dummy_lc_data, oversized_dummy_target_grid):