【问题标题】:Calculating monthly mean from daily netcdf file in python从python中的每日netcdf文件计算月平均值
【发布时间】:2018-01-29 11:21:15
【问题描述】:

您好,我有一个包含每日数据的 netcdf 文件。文件的形状是 (5844, 89, 89) 即 16 年的数据。我试图从每日数据中获取月平均值。我正在寻找类似于熊猫数据框中的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

【问题讨论】:

标签: python numpy netcdf


【解决方案1】:

@jhamman 感谢您推荐xarray.resample。它比我想象的要简单,我的问题的答案是:

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

【讨论】:

    【解决方案2】:

    新版本的xarray,使用方法就简单多了

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

    【讨论】:

      【解决方案3】:

      如果您在 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()
      

      【讨论】:

        猜你喜欢
        • 2021-11-13
        • 2018-09-12
        • 2017-05-05
        • 2021-06-26
        • 2021-07-30
        • 1970-01-01
        • 2021-03-28
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多