A RetroSearch Logo

Home - News ( United States | United Kingdom | Italy | Germany ) - Football scores

Search Query:

Showing content from http://stackoverflow.com/questions/79664933/xarray-apply-function-to-every-element-of-dataset below:

python - Xarray apply function to every element of dataset

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.


RetroSearch is an open source project built by @garambo | Open a GitHub Issue

Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo

HTML: 3.2 | Encoding: UTF-8 | Version: 0.7.4