Python - 碎碎念

Xarray

xr.resample 的等效替换

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
import xarray as xr
import pandas as pd
import numpy as np
np.random.seed(0)
date = pd.date_range('2000-01-01', '2001-12-31', freq='D')
lon = np.arange(0, 360, 2.5)
lat = np.arange(-90, 92.5, 2.5)
data = xr.DataArray(data=np.random.rand(date.size, lon.size, lat.size),
dims=['time', 'lon', 'lat'],
coords=dict(time=date, lon=lon, lat=lat))

# 求 data 各月的最大值
## 法一 resample
mmax = data.resample(time='M').max()

## 法二 groupby
groupbins = xr.DataArray(data=data.indexes['time'].to_period('M').to_timestamp(),
dims=['time'], coords=dict(time=data.time))
mmax = data.groupby(groupbins).max()

.groupby 搭配 .apply() 使用相比 .resample 更自由~

未完待续…