从 python 中的每日 netcdf 文件计算每月平均值

Calculating monthly mean from daily netcdf file in python

您好,我有一个包含每日数据的 netcdf 文件。文件的形状是 (5844, 89, 89) 即 16 年的数据。我试图从每日数据中获取月平均值。我在 pandas 数据框中寻找与 resample 函数类似的函数。在 python 中有没有办法做到这一点? 据我所知,使用 cdo 和 nco 很容易计算,但我正在查看 python。

我用来读取netcdf文件的示例代码是:

import netCDF4
from netCDF4 import Dataset
fh = Dataset(ncfile, mode='r')
time = fh.variables['time'][:]
lon = fh.variables['longitude'][:]
lat = fh.variables['latitude'][:]
data = fh.variables['t2m'][:]
data.shape

@jhamman 谢谢你的建议xarray.resample。它比我想象的要简单,我的问题的答案是:

import xarray as xr
ds = xr.open_dataset(nc_file)
monthly_data = ds.resample(freq = 'm', dim = 'time', how = 'mean')

新版本的xarray,用法简单多了,如下

monthly_data=ds.resample(time='m').mean()

如果您在 Linux 或 macOS 中工作,这可以使用 nctoolkit 轻松完成,它使用 CDO 作为后端。 (安装说明here)。

如果你想得到月均值,你只需要以下内容:

import nctoolkit as nc
data = nc.open_data(ncfile)
data.tmean(["year", "month"])

这可以绘制:

data.plot()

如果您想将其转换为 pandas 数据框:

df = data.to_dataframe()