Add value to all coords in xarray

HI All,

I think this is probably a really easy one but for the life of me i cant find the solution online and the xarray docs don’t seem to have a clear answer to this .

I have taken some of the Global wind atlas data and converted this into a NetCDF file and opened via xarray . The data structure looks like this :

Now I want to add two values, one variable and one coordinate to all latitudes and longitudes. I basically want to add Frequency(variable ) and Sector (Coordinate …I think) so that for every latitude and long i would have wind speed, and freq (allowing me to plot a wind rose)

I should probably note that I am using fake data for freq here , as I am really trying to work out the development of a Plotly-Dash app with a map of wind speed where the user can click on a location and get wind speed and a wind rose . So i am not overly concerned about the accuracy of the data at this stage (this will come later) just want to figure out the bones of the app with fake data.

I have tried the below but this results in a **ValueError** : different number of dimensions on data and dims: 1 vs 3

freq = np.array([7,8,10,5,5,5,15,15,9,7,8,6])
Sector = np.array([0,1,2,3,4,5,6,7,8,9,10,11])
lat = DS['lat'].values
lon = DS['lon'].values


fq = xr.DataArray(freq, coords={ 'lat':lat,'lon':lon,'Sector': Sector},
              dims=['lat','lon','Sector'])

Thanks in advance

David

Hi David,

Here is some code that might help:

# Build something like the WS dataset with dimensions of lat and lon
lon = np.arange(-180, 180)
lat = np.arange(-90, 90)
ws = np.zeros([len(lat), len(lon)])
ws_arr = xr.DataArray(ws, coords={'lat': lat, 'lon': lon}, dims=['lat', 'lon'])
print(ws_arr.shape)

# Create the freqs DataArray
# The freqs array needs to have the right dimensions for the DataArray you are defining
# (len(lat), len(lon), len(sector)) in this case
sector = np.arange(0, 12)
freqs = np.zeros([len(lat), len(lon), len(sector)])
freqs_arr = xr.DataArray(freqs, coords={'lat': lat, 'lon': lon, 'sector': sector}, dims=['lat', 'lon', 'sector'])
print(freqs_arr.shape)

# If you wanted to set all the locations to have the same sector frequencies
freqs_arr[:,:,:] = np.array([7,8,10,5,5,5,15,15,9,7,8,6])

# Create a dataset object containing both the wind speeds and the frequencies
ds = xr.Dataset()
ds['freqs'] = freqs_arr
ds['ws'] = ws_arr
print(ds)

# Get the ws and freq values at a certain coordinate
print(ds.sel(lat=50, lon=50))

Cheers,
Jon

1 Like

@joncollins Thanks very much , that is exactly what I needed .

Congratulations , you receive the honour of the first solution on PY_WRAM :slight_smile:

1 Like

Hi David,

You could also take a look at Windkit, it has several convince functions for making dummy data in its empty subpackage. Two things to note

  1. We have canonicalized the names south_north and west_east for our lat/lon like dimension, so you would need to rename those first.
  2. We require a coordinate reference system on all windkit objects, for lat/lon objects, we typically use the EPSG code for the WGS84 datum “4326”.
import windkit
import windkit.empty
import xarray as xr

ds = DS.rename(lat="south_north", lon="west_east")
ds = windkit.add_crs(ds, 4326)
xr = xr.merge([ds, windkit.empty_bwc(ds)["wdfreq"]])

The result will look something like:

<xarray.Dataset>
Dimensions:       (south_north: 10, west_east: 12, sector: 12)
Coordinates:
  * south_north   (south_north) int64 50 51 52 53 54 55 56 57 58 59
  * west_east     (west_east) int64 0 1 2 3 4 5 6 7 8 9 10 11
    crs           int8 0
    sector_ceil   (sector) float64 15.0 45.0 75.0 105.0 ... 285.0 315.0 345.0
    sector_floor  (sector) float64 345.0 15.0 45.0 75.0 ... 255.0 285.0 315.0
  * sector        (sector) float64 0.0 30.0 60.0 90.0 ... 270.0 300.0 330.0
Data variables:
    ws            (south_north, west_east) float64 0.0 0.0 0.0 ... 0.0 0.0 0.0
    wdfreq        (sector, south_north, west_east) float64 0.0888 ... 0.04758
Attributes:
    Conventions:  CF-1.8
    history:      2022-08-08T09:03:31:\twindkit==0.5.1\twindkit.create_datase...