What would be the best way to index a 2D xarray dataarray using "where" along a specific dimension using 1-D array? Here is an example:
da = xr.DataArray(
np.random.rand(4, 3),
[
("time", pd.date_range("2000-01-01", periods=4)),
("space", ["IA", "IL", "IN"]),
],)
>>> da
<xarray.DataArray (time: 4, space: 3)>
array([[0.26519114, 0.60342615, 0.49726218],
[0.02599198, 0.91702113, 0.7771629 ],
[0.1575904 , 0.25217269, 0.74094842],
[0.7581441 , 0.83447034, 0.31751737]])
and I have a 1-D array/list:
I = [1,0,1,1]
My goal is to get all the rows where I==1. What I do right now is something like this:
I2 =np.repeat(I,repeats=da.shape[1],axis=0).reshape(da.shape)
>>> da.where(I2==1)
<xarray.DataArray (time: 4, space: 3)>
array([[0.26519114, 0.60342615, 0.49726218],
[ nan, nan, nan],
[0.1575904 , 0.25217269, 0.74094842],
[0.7581441 , 0.83447034, 0.31751737]])
Is there another way to do this?