setting values below a threshold to the threshold

2019-07-14 13:23发布

I want to set all values below a constant c to c itself in a netcdf file: file.nc

A solution using climate data operators (CDO) would be

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

But is there a neater/shorter way to do this?

3条回答
爷的心禁止访问
2楼-- · 2019-07-14 14:09

Using Python with NumPy and netCDF4 you could do the following:

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

Good luck!

查看更多
叛逆
3楼-- · 2019-07-14 14:17

ncap2's clipping operator is most concise:

ncap2 -s 'x=x>>100' in.nc out.nc
查看更多
我只想做你的唯一
4楼-- · 2019-07-14 14:28

You can use NCO's ncap2 to do this easily.

For example, set all values of x below 100 to 100 in file.nc and output in file2.nc:

>>> ncap2 -s 'where(x<100.) x=100;' file.nc -O file2.nc 
查看更多
登录 后发表回答