2017-07-11 31 views
2

我的問題是,我想在python中使用xarray庫的簡單功能,但我碰到問題與時間維度的情況下聚合數據。錯誤的時間維度後,與圖書館xarray groupby(python)

我打開了一個數據集,其中包含2013年的日常數據: datset=xr.open_dataset(filein)

文件的內容是:

<xarray.Dataset> 
Dimensions:  (bnds: 2, rlat: 228, rlon: 234, time: 365) 
Coordinates: 
    * rlon   (rlon) float64 -28.24 -28.02 -27.8 -27.58 -27.36 -27.14 ... 
    * rlat   (rlat) float64 -23.52 -23.3 -23.08 -22.86 -22.64 -22.42 ... 
    * time   (time) datetime64[ns] 2013-01-01T11:30:00 ... 
Dimensions without coordinates: bnds 
Data variables: 
    rotated_pole |S1 '' 
    time_bnds  (time, bnds) float64 1.073e+09 1.073e+09 1.073e+09 ... 
    ASWGLOB_S  (time, rlat, rlon) float64 nan nan nan nan nan nan nan nan ... 
Attributes: 
    CDI:      Climate Data Interface version 1.7.0 (http://m... 
    Conventions:    CF-1.4 
    references:    http://www.clm-community.eu/ 
    NCO:      4.6.7 
    CDO:      Climate Data Operators version 1.7.0 

當我現在使用的GROUPBY方法來計算月平均,時間維度被破壞:

datset.groupby('time.month') 
<xarray.core.groupby.DatasetGroupBy object at 0x246a250> 
>>> datset.groupby('time.month').mean('time') 
<xarray.Dataset> 
Dimensions: (bnds: 2, month: 12, rlat: 228, rlon: 234) 
Coordinates: 
    * rlon  (rlon) float64 -28.24 -28.02 -27.8 -27.58 -27.36 -27.14 ... 
    * rlat  (rlat) float64 -23.52 -23.3 -23.08 -22.86 -22.64 -22.42 -22.2 ... 
    * month  (month) int64 1 2 3 4 5 6 7 8 9 10 11 12 
Dimensions without coordinates: bnds 
Data variables: 
    time_bnds (month, bnds) float64 1.074e+09 1.074e+09 1.077e+09 1.077e+09 ... 
    ASWGLOB_S (month, rlat, rlon) float64 nan nan nan nan nan nan nan nan ... 

現在我有一個代替時間維度值爲1到12的月份維度。這是「均值」函數的副作用嗎?只要我不使用這個平均函數,時間變量就會被保留。

我做錯了什麼?文檔和此論壇中給出的示例似乎有不同的行爲。在那裏,除了每個月的第一個日期被使用之外,時間戳被保留。

我可以重塑我以前的時間維度嗎?如果我想要有表示月中中間的時間戳和表示每個平均值(即月初,月末)的間隔的'time_bounds'。

感謝您的幫助,羅尼

+0

我發現輸入文件中座標時間的calendar-attribute保存了'proleptic_gregorian'。也許,這會導致很大的問題。但是,這是大氣科學的一個標準屬性。 –

回答

1

你描述的是預期的行爲:當你.groupby和應用縮小功能mean,你聚集在尺寸由指數更換該組 - 在這種情況下是12個月。

想象一下你有一個多年的時間系列。然後ds.groupby('time.month').mean(dim='time')爲您提供(例如,所有「1月份」合併成一個平均值)的每個月的每月的平均值。

你確定你不想採取月平均值?然後ds.resample(time='1m').mean(dim='time')是你需要的,它實際上會給你一個適當的時間維度。

但是,如果您沒有想多年聚集的平均水平,但要適當time維度,那麼你就可以time指數像這樣更換month指數:

ds['month'] = [datetime.datetime(2017, month, 1) for month in ds['month'].values] 
ds = ds.rename({'month': 'time'}) 

哪裏2017是您選擇的某年作爲您每月指數的年份。