Skip to content

Function in xarray to regroup monthly data into months and # of years #5119

Answered by mathause
pecos27 asked this question in Q&A
Discussion options

You must be logged in to vote

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

Replies: 3 comments 12 replies

Comment options

You must be logged in to vote
3 replies
@chiaral
Comment options

@pecos27
Comment options

@pecos27
Comment options

Comment options

You must be logged in to vote
4 replies
@pecos27
Comment options

@dcherian
Comment options

@pecos27
Comment options

@dcherian
Comment options

Comment options

You must be logged in to vote
5 replies
@pecos27
Comment options

@kuchaale
Comment options

@mathause
Comment options

@awais307
Comment options

@pecos27
Comment options

Answer selected by pecos27
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet
6 participants