簡體   English   中英

使用庫 xarray (python) 進行 groupby 后時間維度錯誤

[英]Wrong time dimension after doing a groupby with library xarray (python)

我的問題是我想在 python 中使用 xarray-library 的簡單功能,但是在聚合數據的情況下我遇到了時間維度的問題。

我打開了一個數據集,其中包含 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' 指示每個平均值的間隔,即月初、月底,該怎么辦。

謝謝你的幫助,羅尼

您所描述的是預期行為:當您使用.groupby聚合並應用諸如mean之類的歸約函數時,您聚合的維度將替換為組索引- 在這種情況下為 12 個月。

假設您有一個多年時間序列。 然后ds.groupby('time.month').mean(dim='time')為您提供任何一年中每個月平均值(例如,所有“一月”合並為一個平均值)。

您確定不想取月平均值嗎? 然后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是您選擇作為月度指數年份的年份。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM