简体   繁体   English

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

[英]Calculating monthly mean from daily netcdf file in python

Hello I have a netcdf file with daily data.您好,我有一个包含每日数据的 netcdf 文件。 Shape of the file is (5844, 89, 89) ie 16 years data.文件的形状是 (5844, 89, 89) 即 16 年的数据。 I tried to get monthly average from daily data.我试图从每日数据中获得月平均值。 I am looking for simillar to resample function in pandas dataframe.我正在寻找类似于在熊猫数据框中resample功能。 Is there anyways to do that in python.无论如何在python中做到这一点。 As I know it is very easy to calculate by using cdo and nco but I am looking in python.据我所知,使用 cdo 和 nco 很容易计算,但我正在寻找 python。

Sample code that I used to read netcdf file is:我用来读取 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 Thank you for suggesting xarray.resample . @jhamman 感谢您建议xarray.resample It is simpler than I thought and the answer to my question is:它比我想象的要简单,我的问题的答案是:

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()

If you are working in Linux or macOS this can be easily done using nctoolkit, which uses CDO as a backend.如果您在 Linux 或 macOS 上工作,这可以使用 nctoolkit 轻松完成,它使用 CDO 作为后端。 (Installation instructions here ). (安装说明在这里)。

If you want to get the monthly mean, you just need the following:如果您想获得月均值,您只需要以下内容:

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

This can be plotted:这可以绘制:

data.plot()

If you wanted to convert it to a pandas dataframe:如果您想将其转换为熊猫数据框:

df = data.to_dataframe()

May I also suggest the following solution: 我还可以提出以下解决方案:

data = fh.variables['t2m'][:] # The t2m variable is pulled out of the file as 'data'
stat1 = data.mean() # mean
stat2 = data.std() # standard dev

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM