【问题标题】:How to perform comparisons on numpy arrays (from netCDF files) using python?如何使用 python 对 numpy 数组(来自 netCDF 文件)进行比较?
【发布时间】:2015-06-08 11:38:04
【问题描述】:

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

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] 中检查的信息。所以我需要遍历维度,但我不知道该怎么做,也不知道是否有最简单的方法。谢谢

【问题讨论】:

    标签: python comparison netcdf


    【解决方案1】:

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

    问题在于,给定一个 numpy 向量 rr[:] == 2(或 r[:] > 0)返回一个布尔数组而不是单个布尔值。因此它不应该用在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 中循环索引要高效得多,应该尽可能使用。

    【讨论】:

    • 非常感谢,第二种方法正是我需要的。感谢您的建议。
    • 另外,根据您的说明更新了问题的标题
    【解决方案2】:

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

    例如,如果你想沿时间轴应用函数 srf,你会这样做

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

    【讨论】:

      猜你喜欢
      • 2013-05-09
      • 1970-01-01
      • 1970-01-01
      • 2022-01-23
      • 2014-07-11
      • 2014-09-21
      • 1970-01-01
      • 2012-08-22
      • 1970-01-01
      相关资源
      最近更新 更多