本文介绍了Python:使用netCDF4替换netcdf文件中的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个带有多个值的netcdf文件< 0.我想用一个值替换所有的值(例如-1).如何使用netCDF4做到这一点?我正在这样读取文件:

I have a netcdf file with several values < 0. I would like to replace all of them with a single value (say -1). How do I do that using netCDF4? I am reading in the file like this:

import netCDF4

dset      = netCDF4.Dataset('test.nc')
dset[dset.variables['var'] < 0] = -1

推荐答案

如果要将数据保留在netCDF变量对象中,这应该可以工作:

If you want to keep the data in the netCDF variable object, this should work:

import netCDF4

dset = netCDF4.Dataset('test.nc', 'r+')

dset['var'][:][dset['var'][:] < 0] = -1

dset.close() # if you want to write the variable back to disk

如果您不想写回磁盘,请继续获取numpy数组并对其切片/分配:

If you don't want to write back to disk, go ahead and just get the numpy array and slice/assign to it:

data = dset['sea_ice_cover'][:]  # data is a numpy array
data[data < 0] = -1

这篇关于Python:使用netCDF4替换netcdf文件中的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-23 21:45