-
|
Along a dimension or in a groupby group, I want to perform a reduction that checks that there is only one unique value in the group and returns it. I couldn't figure out how to apply the below with import numpy as np
import xarray as xr
def the_unique(x):
"""Return _the_ non-NaN unique value or raise ValueError."""
uns = np.unique(x)
uns = uns[~np.isnan(uns)]
if uns.size == 1:
return uns[0]
elif uns.size == 0:
raise ValueError("no non-NaN values")
else:
raise ValueError("more than one unique value")
assert the_unique([1, 1, 1]) == 1
x = np.tile(np.arange(3)[:,np.newaxis], 3) # each row has one unique value
np.testing.assert_equal(
np.apply_along_axis(the_unique, 1, x),
[0, 1, 2]
)
da = xr.DataArray(x, dims=["y", "x"])
# xr.apply_ufunc(...) ?Example situation:
|
Beta Was this translation helpful? Give feedback.
Answered by
dcherian
Sep 30, 2022
Replies: 1 comment 1 reply
-
|
This should work with For
|
Beta Was this translation helpful? Give feedback.
1 reply
Answer selected by
zmoon
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This should work with
reduce? Alsopd.uniqueis usually faster thannp.uniqueand won't return multiple NaNsFor
apply_ufunc:input_core_dimsshould be the dimension you're reducingoutput_core_dimsapply_along_axisusevectorize=True.You might even try