0

I currently have to do some calculations on a netcdf dataset. For this, I have to apply a function to each non-NaN element.
Here is my current approach:

import xarray as xr
def calc_things(wind_speed):
 if np.isnan(wind_speed):
 return np.nan
 if wind_speed<3:
 return 0
 if wind_speed>11.3:
 return 100
 
 # do math stuff here
if __name__ == "__main__":
 with xr.open_dataset("input.nc") as df:
 wind_data = df['sfcWind']
 
 wind_applied = xr.apply_ufunc(calc_things, wind_data, vectorize=True)
 
 ds.to_netcdf("modified.nc")

Can somebody tell me if this is the right way to do it? I am also wondering if there is a better way to handle the NaN values instead of having an if-statement in the function.
All help is appreciated.

asked Jun 13, 2025 at 13:31
3
  • If this snippet gives expected results, can you elaborate what you mean by the 'right' way to do things? Commented Jun 16, 2025 at 15:34
  • Just because something works doesn't mean that it is the best way to do it. For example you can append to a numpy array, even though it is not encouraged due to performance. Commented Jun 25, 2025 at 8:15
  • Maybe you should try code review. On Stack Overflow we ask specific question on specific problem. Do you have a performance problem for example, sine you mentioned it? Commented Jul 14, 2025 at 4:56

0

Know someone who can answer? Share a link to this question via email, Twitter, or Facebook.

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.