如何使用 python 对 numpy 数组(来自 netCDF 文件)进行比较?

How to perform comparisons on numpy arrays (from netCDF files) using python?

我正在编写一个 python 脚本,它读取两个不同的 netCDF 文件,在对变量进行评估后进行一些计算,我的想法是(代码想法的一个例子是真实的太长了):

import netCDF4
import numpy as np
#other modules loaded...

#Values
a = 2
b = 4
c = 1

def srf(r, h):
    if r[:] == 2:
        if h[:] > 0:
            surf = 1 + b
        else:
            surf = a + b 
    else:
        surf = a - c

return surf

path_file : /home/file.nc
fhp = Dataset(path_file, r+)
ra = fhp.variables['VAR'][:]
path_file2 : /home/file2.nc
fhp2 = Dataset(path_file2, r+)
hu = fhp2.variables['VAR2'][:]   

#Call the Function
srf(ra, hu)       

每个 netCDF 文件都有 3 个维度,如果我尝试 运行 这个代码,我会得到这个错误

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

我需要在 las 二维中执行该功能,这些维度包含用于检查域 [TSTEP、ROW、COL] 的信息。所以我需要遍历维度,但我不确定该怎么做,我不知道是否有最简单的方法。谢谢

这个问题与 netCDF 无关,而是关于从 netCDF 文件中获取的 numpy 数组的操作。

问题是给定一个 numpy 向量 rr[:] == 2(或 r[:] > 0)returns 一个布尔数组而不是一个布尔值。因此,不应在 if 结构中使用它。根据您要实现的目标,您可以使用以下方法,

  • 改用(r[:] == 2).any()(r[:] == 2).all()
  • 使用更复杂的索引,例如,

    import numpy as np
    
    def srf(r, h):
        mask_r = (r[:] == 2)
        mask_h = (h[:] > 0)
        surf  = np.ones(r.shape)*(a-c)
        surf[mask_r&mask_h] = 1 + b
        surf[mask_r&(~mask_h)] = a + b
        return surf
    

请参阅有关 advanced indexing 的 numpy 文档以获取更多详细信息。这种方法比 python 中的索引循环效率高得多,应尽可能使用。

此外,如果您想沿特定轴应用函数,可以使用 numpy.apply_along_axis。

例如,如果您想沿时间轴应用函数 srf,您可以

将 numpy 导入为 np srf_arr = np.apply_along_axis(srf, axisnumber, arrayname)