要将grib2文件转换为nc文件,需要安装python库pygrib和netCDF4,然后使用以下代码:

import pygrib
from netCDF4 import Dataset

# 打开grib2文件
grbs = pygrib.open('filename.grib2')

# 创建nc文件
ncfile = Dataset('filename.nc', 'w', format='NETCDF4')

# 定义维度
latitudes, longitudes = grbs[1].latlons()
ncfile.createDimension('latitude', len(latitudes[:,0]))
ncfile.createDimension('longitude', len(longitudes[0,:]))

# 定义变量
lat = ncfile.createVariable('latitude', 'f4', ('latitude',))
lon = ncfile.createVariable('longitude', 'f4', ('longitude',))
temp = ncfile.createVariable('temperature', 'f4', ('latitude', 'longitude',))

# 设置变量属性
lat.units = 'degrees_north'
lon.units = 'degrees_east'
temp.units = 'K'

# 将数据写入nc文件
lat[:] = latitudes[:,0]
lon[:] = longitudes[0,:]
temp[:] = grbs[1].values

# 关闭文件
ncfile.close()
grbs.close()

其中,需要将代码中的'filename.grib2'替换为你要转换的grib2文件名,'filename.nc'替换为你要保存的nc文件名。此外,还可以根据需要更改变量名、单位等属性。

用python把grib2文件转化为nc文件

原文地址: https://www.cveoy.top/t/topic/bqbG 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录