1

This subject refers to this one I closed earlier: NetCDF4 file with Python - Filter before dataframing

After applying the solution of the other topic to reduce an xarray size

data_9 = ds.sel(time=datetime.time(9))

I have an xarray this way:

enter image description here

But I still can and need to reduce it on latitude and longitude For example I want only longitude between -4 and 44

I tried to apply the function sel again but it doesn't seem to work this time :'(

data_9 = ds.sel(time=datetime.time(9)).sel(lon>-4).sel(lon<44)

Doing this it can't recognise lon...

NameError: name 'lon' is not defined

Can someone helps on this too? Thanks

ImFabien75
  • 157
  • 1
  • 9

2 Answers2

0

It seems you have to use where instead of sel here. We can create a condition array just like in numpy and give it to where. The second parameter drop=True removes the data where our condition is falsy. Without it, you would get nans there instead of getting a trimmed dataset.

I am using the same demo dataset used in the other question you linked.

import xarray as xr
import datetime

# Load a demo dataset.
ds = xr.tutorial.load_dataset('air_temperature')

data_9 = ds.sel(time=datetime.time(9))
cond = (-4 < data_9.lon) & (data_9.lon < 44)
data_9 = data_9.where(cond, drop=True) 
Guimoute
  • 4,407
  • 3
  • 12
  • 28
0

Xarray's sel methods can take multiple selectors and windows in the form of slices:

ds_subset = ds.sel(time=datetime.time(9), lon=slice(-4, 44))
jhamman
  • 5,867
  • 19
  • 39