python - xarray groupby 坐标和非坐标变量
问题描述
我正在尝试计算 xarray 中变量的分布。我可以通过将 xarray 转换为 pandas 数据框来实现我想要的,如下所示:
lon = np.linspace(0,10,11)
lat = np.linspace(0,10,11)
time = np.linspace(0,10,1000)
temperature = 3*np.random.randn(len(lat),len(lon),len(time))
ds = xr.Dataset(
data_vars=dict(
temperature=(["lat", "lon", "time"], temperature),
),
coords=dict(
lon=lon,
lat=lat,
time=time,
),
)
bin_t = np.linspace(-10,10,21)
DS = ds.to_dataframe()
DS.loc[:,'temperature_bin'] = pd.cut(DS['temperature'],bin_t,labels=(bin_t[0:-1]+bin_t[1:])*0.5)
DS_stats = DS.reset_index().groupby(['lat','lon','temperature_bin']).count()
ds_stats = DS_stats.to_xarray()
<xarray.Dataset>
Dimensions: (lat: 11, lon: 11, temperature_bin: 20)
Coordinates:
* lat (lat) float64 0.0 1.0 2.0 3.0 4.0 5.0 6.0 7.0 8.0 9.0 10.0
* lon (lon) float64 0.0 1.0 2.0 3.0 4.0 5.0 6.0 7.0 8.0 9.0 10.0
* temperature_bin (temperature_bin) float64 -9.5 -8.5 -7.5 ... 7.5 8.5 9.5
Data variables:
time (lat, lon, temperature_bin) int64 0 1 8 13 18 ... 9 5 3 0
temperature (lat, lon, temperature_bin) int64 0 1 8 13 18 ... 9 5 3 0
有没有办法在不转换为数据框的情况下生成 ds_stats?我曾尝试使用 groupby_bins 但这不会保留坐标。
print(ds.groupby_bins('temperature',bin_t).count())
distributed.utils_perf - WARNING - full garbage collections took 21% CPU time recently (threshold: 10%)
<xarray.Dataset>
Dimensions: (temperature_bins: 20)
Coordinates:
* temperature_bins (temperature_bins) object (-10.0, -9.0] ... (9.0, 10.0]
Data variables:
temperature (temperature_bins) int64 121 315 715 1677 ... 709 300 116
解决方案
使用xhistogram可能会有所帮助。
使用与您在上面设置的相同定义,
from xhistogram import xarray as xhist
ds_stats = xhist.histogram(ds.temperature, bins=bin_t,dim=['time'])
应该做的伎俩。
一个区别是它返回 a DataArray
,而不是 a Dataset
,所以如果你想为多个变量做它,你必须为每个变量单独做,然后重新组合,我相信。
推荐阅读
- python - 如何在没有 Sudo/Root 访问权限的情况下在 Mac 上安装 PIP3(用于 python 3)?
- git - 引用不存在的提交的 Git 子模块
- javascript - Bootstrap 4 模态中的 Cloudinary 响应式图像以适应移动屏幕
- python - 从列中删除数字
- python - 对矩阵运算的精美索引
- python - django & postgres 时区本地时间 vs UTC
- pug - 如何在内联 javascript 中使用 mixin 块?
- python - Django - 从views.py中的模板引用值
- datasette - 未找到登录和哈希页面
- android - 使用 putExtra 传递数据并在 onClick 中使用