[英]How to calculate monthly mean of a time seies data and substract the monthly mean with the values of that month of each year?
[英]Calculate monthly mean from daily data for each year
我已經看到許多如何從多年的每日數據計算月平均值的答案。
但是我想要做的是分別從我的 xarray 中每年的每日數據計算每月平均值。 所以,我想最終得到 2020 年 1 月、2020 年 2 月 ... 2024 年 12 月的每個經緯度網格點的平均值。
我的 xarray 有尺寸 Frozen({'time': 1827, 'lon': 180, 'lat': 90}) 我嘗試使用var_resampled = var_diff.resample(time='1M').mean()
但這計算所有年份的平均值(即 2020-2024 年 1 月的平均值)。
我也試過
def mon_mean(x):
return x.groupby('time.month').mean('time')
# group by year, then apply the function:
var_diff_mon = var_diff.groupby('time.year').apply(mon_mean)
這似乎做我想做的,但我最終得到了不同的維度(即“月”和“年”而不是原始的“時間”維度)。
是否有不同的方法可以分別從每年的每日數據計算每月平均值,或者是否有一種方法可以使上面使用 groupby 的代碼保留與以前相同的時間維度,現在只使用年和月?
PS我也嘗試過“cdo monmean”,但據我所知,這也只是給出了所有年份的月均值。
謝謝!
解決方案我找到了一種使用方法
def mon_mean(x):
return x.groupby('time.month').mean('time')
# group by year, then apply the function:
var_diff_mon = var_diff.groupby('time.year').apply(mon_mean)
然后使用
var_diff_mon.stack(time=("year", "month"))
找回我原來的時間維度
var_diff.resample(time='M')
(或time='MS'
)是否符合您的預期?
讓我們創建一個像你這樣的玩具數據集:
import numpy as np
import pandas as pd
import xarray as xr
dims = ('time', 'lat', 'lon')
time = pd.date_range("2021-01-01T00", "2023-12-31T23", freq="H")
lat = [0, 1]
lon = [0, 1]
coords = (time, lat, lon)
ds = xr.DataArray(data=np.random.randn(len(time), len(lat), len(lon)), coords=coords, dims=dims).rename("my_var")
ds = ds.to_dataset()
ds
讓我們重新采樣:
ds.resample(time="MS").mean()
該數據集現在有 36 個時間步長,與原始數據集中的 36 個月相關聯。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.