【问题标题】:Changing value of a netcdf file for a variable更改变量的 netcdf 文件的值
【发布时间】:2017-07-07 04:30:44
【问题描述】:

我有一个大型的 netcdf 文件,它是三维的。我想用 2 替换 netcdf 文件中变量 LU_INDEX 的所有值 10。

我为此编写了这个 python 脚本,但它似乎不起作用。

filelocation = 'D:/dataset.nc'

ncdataset = nc.Dataset(filelocation,'r')
lat           = ncdataset.variables['XLAT_M'][0,:,:]
lon           = ncdataset.variables['XLONG_M'][0,:,:]
lu_index     = ncdataset.variables['LU_INDEX'][0,:,:]
lu_index_new = lu_index
ncdataset.close()

nlat,nlon=lat.shape

for ilat in range(nlat):
    for ilon in range(lon):
        if lu_index == 10:
          lu_index_new[ilat,ilon] = 2

newfilename = 'D:/dataset.new.nc'
copyfile(ncdataset,newfilename)


newfile     = nc.Dataset(newfilename,'r+')
newfile.variables['LU_INDEX'][0,:,:]   = lu_index_new
newfile.close()

我得到错误:

The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()

我对python不是很有经验,所以如果有更简单的方法可以做到这一点,非常欢迎您发表评论。

【问题讨论】:

    标签: python netcdf


    【解决方案1】:

    你可以试试NCO

    ncap2 -s 'where(LU_INDEX == 10) LU_INDEX=2' in.nc out.nc

    【讨论】:

      【解决方案2】:

      我是这样计算的:

      import netCDF4 as nc
      import numpy as np
      
      pathname = 'D:'
      filename = '%s/dataset.nc'%pathname
      ncfile = nc.Dataset(filename,'r+')
      lu_index = ncfile.variables['LU_INDEX'][:]
      I = np.where(lu_index == 10)
      lu_index[I] = 2
      ncfile.variables['LU_INDEX'][:] = lu_index
      filename.close()
      
      print 'conversion complete'
      

      【讨论】:

      • NCO 和 Python 解决方案之间的简洁差异是惊人的。
      • NCO 也可能快 1000 倍。专业提示:尽可能利用 NCO。
      • 不仅速度更快,而且内存效率更高。这是一组很棒的程序!谢谢查理
      【解决方案3】:

      使用 np.array 可能不适用于具有以下错误的非常大的数据集

      "ValueError: 数组太大;arr.size * arr.dtype.itemsize 大于最大可能大小。"

      CDO 可以是 NCO 以外的好工具,对我来说,它的速度要快得多。

      CDO setvals,10,2 in.nc out.nc
      

      当您必须在同一个 nc 文件中替换多个变量中的值时(例如替换缺失值表示),它特别快。 可以使用“setrtoc”代替 setval 来指定范围。

      【讨论】:

        猜你喜欢
        • 2020-09-11
        • 1970-01-01
        • 2017-02-19
        • 1970-01-01
        • 2022-10-06
        • 2023-04-03
        • 2021-12-06
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多