我有一个netcdf文件,其中有几个值< 0.我想用一个值(比如-1)替换所有这些值。我如何使用netCDF4做到这一点?我在这样的文件中读到:
import netCDF4
dset = netCDF4.Dataset('test.nc')
dset[dset.variables['var'] < 0] = -1
答案 0 :(得分:7)
如果要将数据保存在netCDF变量对象中,则应该起作用:
a = Array.wrap(params[:a]).join(', ')
<% unless a.blank? %>
<%= a%>,
<% end %>
b = Array.wrap(params[:where]).join(' AND ')
<% unless params[:dedup] %>
table_name
WHERE <%= input_data_filter %>
<% unless b.blank? %>
AND <%= b %>
<% end %>
AND c - d <= <%= f%>
<% else %>
如果您不想写回磁盘,请继续使用numpy数组并切片/分配给它:
import netCDF4
dset = netCDF4.Dataset('test.nc')
dset['var'][:][dset['var'][:] < 0] = -1
dset.close() # if you want to write the variable back to disk
答案 1 :(得分:6)
对我来说,之前的答案不起作用,我解决了它:
dset = netCDF4.Dataset('test.nc','r+')
dset.variables['var'][:]
... your changes ...
dset.close()
答案 2 :(得分:2)
我知道OP需要一个python解决方案,但是如果有人只想执行此任务,还有一种快捷方法可以从命令行使用nco来完成:
ncap2 -s 'where(x<0.) x=-1;' input.nc -O output.nc
根据这篇文章:setting values below a threshold to the threshold in a netcdf file
答案 3 :(得分:0)
为了能够使用方程式进行条件计算,而不是仅使用常数进行计算,我根据@jhamman的代码对形状为(month,lats,lons)的变量进行了条件迭代,如下所示:
import netCDF4 as nc
import numpy as np
import time
Tmin = -1.7
Tmax = 4.9
perc = (Tmax-Tmin)/100
lats = np.arange(0,384,1)
lons = np.arange(0,768,1)
months = [0,1]
dset = nc.Dataset('path/file.nc', 'r+')
start = time.time()
dset['var'][:][dset['var'][:] < Tmin] = 100
step1 = time.time()
print('Step1 took: ' + str(step1-start))
dset['var'][:][dset['var'][:] > Tmax] = 0
step2 = time.time()
print('Step2 took: ' + str(step2 - step1))
#start iteration of each dimension to alter individual values according to equation new_value = 100-((Old_value +1.8)/1%)
for m in months:
newstart = time.time()
for i in lats:
step3 = time.time()
print('month lats lat layer '+str(i)+' took: '+str(step3-newstart) +'s')
for j in lons:
if dset['var'][m,i,j] < Tmax and dset['var'][m,i,j] > Tmin:
dset['var'][m,i,j] = 100-((dset['var'][m,i,j]+1.8)/perc)
end = time.time()
print('One full month took: ' + str(end-start) +'s')
dset.close()
但是,问题在于它变成了非常慢的代码。
Step1 took: 0.0343s
Step2 took: 0.0253s
month lats lat layer: 0.4064s
One full month took 250.8082s
由于迭代,这是逻辑。但是我想知道你们中是否有人知道如何加快速度。对于这个目标,迭代真的必要吗?