【问题标题】:setting values below a threshold to the threshold in a netcdf file将低于阈值的值设置为 netcdf 文件中的阈值
【发布时间】:2016-09-06 22:52:03
【问题描述】:

我想在 netcdf 文件中将常量 c 下的所有值设置为 c 本身:file .nc

使用气候数据运营商 (CDO) 的解决方案是

cdo mul -gec,$c file.nc file.nc t1.nc
cdo add -mulc,$c -ltc,$c file.nc t1.nc output.nc
rm -f t1.nc

但是有没有更简洁/更短的方法来做到这一点?

【问题讨论】:

    标签: bash netcdf nco cdo-climate


    【解决方案1】:

    您可以使用NCO's ncap2 轻松完成此操作。

    例如在file.nc中设置x的所有值低于100到100,并在file2.nc中输出:

    >>> ncap2 -s 'where(x<100.) x=100;' file.nc -O file2.nc 
    

    【讨论】:

      【解决方案2】:

      将 Python 与 NumPy 和 netCDF4 结合使用,您可以执行以下操作:

      import numpy as np
      from netCDF4 import Dataset
      
      dataset = Dataset('/path/to/dataset','r+')
      
      data = dataset.variables['data_variable_name'][:]
      
      threshold = 100 # or whatever your constant c is
      
      # np.where(condition, value if true, value if false)
      new_data = np.where(data < threshold, threshold, data)
      
      # Write your new data back to the NetCDF file
      dataset.variables['data_variable_name'][:] = new_data[:]
      
      dataset.close()
      

      祝你好运!

      【讨论】:

      • 我同意这是可行的,但我认为一般来说data[data &lt; threshold] = threshold 是在 Python 中执行此操作的更快方法。
      • 我同意。我总是忘记这个较短的语法。现在我不会了!
      • 虽然 data[data
      【解决方案3】:

      ncap2的裁剪算子最简洁:

      ncap2 -s 'x=x>>100' in.nc out.nc
      

      【讨论】:

      • 此命令有效,但会默默地转换数据,例如浮动到双倍(ncap2 版本 4.3.7)
      • 那是一个相当旧的版本。在当前版本中工作正常(浮点数保持为浮点数)。刚刚试了一下。
      • @CharlieZender 认为我有一个包含许多时间步长的大型 NETCDF。以上将导致内存问题。如何在不读取整个数据文件的情况下一次将上述代码行应用于 1 个时间步来执行上述操作?
      • 您可以尝试使用手册中描述的 ncap2 的数组语法一次剪切 N 个切片。如果这不起作用,那么您可以使用 ncks 拆分文件,使用 ncap2 剪辑,然后使用 ncrcat 重新组装。
      【解决方案4】:

      气候数据运营商 (CDO) 使用 expr 还可以更有效地执行此操作。将this post中的示例改编为this question中的具体示例,假设变量的名称是x,常量是c,那么命令会是什么像这样:

      cdo -expr,'x = ((x > c)) ? x : c' infile.nc outfile.nc
      

      其中?: 是三元条件运算符,x ? y : z 表示y if x not equal 0, else z。有关运算符和表达式的更多信息,请参阅CDO Manual,第 2.7.1 节。

      【讨论】:

      • 非常不错,没想到expr...
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-04-04
      • 2020-10-14
      • 2020-09-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多