简体   繁体   English

引入新坐标“冬天”

[英]Introduce new coordinate 'winter'

I have an xarray DataSet with daily data of a variable for several years (but for each year I just have Jan, Feb, Mar and Dec).我有一个 xarray 数据集,其中包含几年的变量每日数据(但每年我只有一月、二月、三月和十二月)。

I don't have a problem accessing for example a specific year-month combination, like "show me the data from jan2009".例如,我在访问特定的年月组合时没有问题,例如“向我展示 jan2009 的数据”。 But I am struggling to introduce a new coordinate, that allows me to access但我正在努力引入一个新坐标,它允许我访问

  • winter number 1 (which contains the daily data for Dec 2008, Jan 2009, Feb 2009 and Mar 2009),冬季编号 1(包含 2008 年 12 月、2009 年 1 月、2009 年 2 月和 2009 年 3 月的每日数据),

  • winter number 2 (which contains the daily data for Dec 2009, Jan 2010, Feb 2010 and Mar 2010),冬季编号 2(包含 2009 年 12 月、2010 年 1 月、2010 年 2 月和 2010 年 3 月的每日数据),

  • winter number 3 and so on.冬天3号等等。

This is to give you an idea how my DataSet 'data' looks like:这是为了让您了解我的 DataSet 'data' 的样子:

<xarray.Dataset>
Dimensions:    (latitude: 1, longitude: 1440, time: ...)
Coordinates:
  * longitude  (longitude) float32 -180.0 -179.75 -179.5 ... 179.25 179.5 179.75
  * latitude   (latitude) float32 60.0
  * time       (time) datetime64[ns] 1980-01-01 ... 2010-03-28
Data variables:
    u          (time, latitude, longitude) float32 dask.array<shape=(..., 1, 1440), chunksize=(..., 1, 1440)>

Here is what data.time looks like:这是data.time的样子:


<xarray.DataArray 'time' (time: 476)>
array(['1980-01-01T00:00:00.000000000', '1980-01-01T06:00:00.000000000',
       '1980-01-01T12:00:00.000000000', ..., '1981-02-28T06:00:00.000000000',
       '1981-02-28T12:00:00.000000000', '1981-02-28T18:00:00.000000000'],
      dtype='datetime64[ns]')
Coordinates:
  * time     (time) datetime64[ns] 1980-01-01 ... 1981-02-28T18:00:00
Attributes:
    long_name:  time

You can make a function to define your new coordinates (Winter).您可以制作 function 来定义您的新坐标(冬季)。

def get_winter_year(dates):

    y = dates.dt.year.values
    m = dates.dt.month.values
    ym = list(zip(y,m))

    return [(ym[i][0] - ym[0][0] + 1) if ym[i][1] < 4 else (ym[i][0] - ym[0][0] + 2) for i in range(len(ym))]

Then we can groupby our new coordinate and make calculations.然后我们可以根据我们的新坐标进行分组并进行计算。

airtemps = xr.tutorial.open_dataset('air_temperature')
d = airtemps.assign_coords(time=get_winter_year(airtemps['time']))
d = d.rename({'time' : 'Winter'})
d.groupby('Winter').mean(dim=('Winter'))

> <xarray.Dataset> Dimensions:  (Winter: 3, lat: 25, lon: 53)
> 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   
> * Winter   (Winter) int64 1 2 3 
>  Data variables:
>      air  (Winter, lat, lon) float32 244.61775 244.4874 ... 297.86255

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM