【问题标题】:How to calculate a yearly sum xarray from a monthly means masked array?如何从每月均值屏蔽数组计算每年的总和 xarray?
【发布时间】:2021-11-14 04:38:24
【问题描述】:

我想计算高于 7 和低于 33 摄氏度的日平均气温的年总和。这是针对生物学相关学位天数指数的定制计算。我想在 python 中做这个计算,我想用 Python 的方式来做,意思是,使用 xarray 和 numpy 等知名包中已经制作的函数。

我正在使用TG dataset from CDS。它采用 netCDF 格式,时间跨度从 1981 年到 2010 年。 我被困在做这个计算。我能够使用以下命令将数据集重新采样为月平均值:

monmean = ds.TG.resample({"time":"1MS"}).mean()

现在我需要对每日温度平均值的月平均值进行上述年度总和,但我找不到避免添加那些超出我定义的区间的值的方法。我试着用这样的面具:

masked_array = ma.masked_outside(monmean, 7+273.15, 33+273.15)
masked_monmean = np.ma.masked_where(np.ma.get_mask(masked_array), monmean)

但是随后发生的事情是 masked_monmean 是一个 maskedarray 并且 xarray 函数 resample 不再适用。

ymonmeansum = masked_monmean.data.resample({'time':'YS'}).sum()

AttributeError: 'numpy.ndarray' object has no attribute 'resample'

你知道我该如何解决这个问题吗?

【问题讨论】:

  • 在第三个代码块中应该是 ymonmeansum = masked_monmean.resample({'time':'YS'}).sum() AttributeError: 'MaskedArray' object has no attribute 'resample

标签: python numpy mask netcdf python-xarray


【解决方案1】:

您可以在resample 之前使用where 方法:

mask = ds['TG'].isel(time=0)
ds['TG'].where(7.<=ds['TG']).where(ds['TG']<=33.).resample(time='M').mean().where(mask)

where 将不满足布尔方程的值设置为 nan,平均值不包括 nan 值。

【讨论】:

  • 感谢您的评论。 .where 的问题是它将 nan 值替换为零,我也不知道如何避免这种情况。你知道吗?
  • 我相信where 不会用零替换值。您可以尝试绘制一个网格的时间序列以确保它:ds['TG'].where(7.&lt;=ds['TG']).where(ds['TG']&lt;=33.).isel(lon=0, lat=0).plot().
  • 不幸的是,它正在这样做。检查一下: array([[[0., 0., 0., ..., 0., 0., 0 .], [0., 0., 0., ..., 0., 0., 0.], [0., 0., 0., ..., 0., 0., 0.] , ..., [0., 0., 0., ..., 0., 0., 0.], [0., 0., 0., ..., 0., 0., 0 .], [0., 0., 0., ..., 0., 0., 0.]], ...
  • 这是在我这样做之后:yearlysum = monmean.where(7.+273.15 >= monmean).where(monmean
  • 如果我在 sum() 中引入 min_count=1,零值问题就解决了,如下所示:yearlysum = monmean.where(7.+273.15 >= monmean).where(monmean stackoverflow.com/questions/33448003/…
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-12-18
  • 2019-10-09
  • 2021-09-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-03-28
相关资源
最近更新 更多