-
I have a 3D array with time (in months), y, and x. I'm hoping to split this xarray dataframe into # of months (january - december), all the years of that month, y, and x. I tried using:
however it appears to return just an empty dataframe:
Is it possible to do this in xarray? |
Beta Was this translation helpful? Give feedback.
Replies: 3 comments 12 replies
-
you can iterate across the group
you could create a new dataset with another dimension (year) through this loop, or you could simply apply your function to each month separately. |
Beta Was this translation helpful? Give feedback.
-
One option is See #2419 for an alternative way. I think the real solution is to support |
Beta Was this translation helpful? Give feedback.
-
Does the following snippet do what you want? def to_monthly(ds):
year = ds.time.dt.year
month = ds.time.dt.month
# assign new coords
ds = ds.assign_coords(year=("time", year.data), month=("time", month.data))
# reshape the array to (..., "month", "year")
return ds.set_index(time=("year", "month")).unstack("time") Example # read tutorial data and resample to monthly
air = xr.tutorial.open_dataset("air_temperature").resample(time="M").mean()
to_monthly(air)
Out[8]:
<xarray.Dataset>
Dimensions: (lat: 25, lon: 53, month: 12, year: 2)
Coordinates:
* lat (lat) float32 75.0 72.5 70.0 67.5 65.0 ... 25.0 22.5 20.0 17.5 15.0
* lon (lon) float32 200.0 202.5 205.0 207.5 ... 322.5 325.0 327.5 330.0
* year (year) int64 2013 2014
* month (month) int64 1 2 3 4 5 6 7 8 9 10 11 12
Data variables:
air (lat, lon, year, month) float32 244.5 240.7 248.3 ... 298.8 297.7 edit: use |
Beta Was this translation helpful? Give feedback.
Does the following snippet do what you want?
Example