对Numpy数组进行条件检查的有效方法

2024-09-30 06:11:47 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试对numpy数组执行一些条件检查,我的代码现在不是很python。有人能建议更有效的方法来写下面的代码吗?在

  1. h是一个二维浮点数数组,其维数为nrows*ncol
  2. ibound是一个二维整数数组,其维数为nrows*ncol
  3. L1TopOld是一个二维浮点数数组,其维数为nrows*ncol
eps = 1.0e-04
#Fill in gaps in the surfaces#####################################
for i in range(nrows):
  for j in range(ncols):
      if (ibound[i,j] == 1 and fabs(h[i,j]-nodata) <= eps):
          h[i,j] = L1TopOld[i,j]

Tags: 方法代码innumpyforrange数组eps
3条回答

您只需继续矢量方式:

cond = (ibound == 1) & (np.fabs(h - nodata) <= eps)
h[cond] = L1TopOld[cond]

让我们看一个例子(我使用的是previous comment)中提出的一个例子:

^{pr2}$

你的

您可以使用^{}。首先,让我们制作一些玩具数据(顺便说一句,如果你自己做这部分的话会有帮助):

>>> h = np.random.random((3,4))
>>> nodata = 10
>>> h.flat[[2,3,4,7,8,9]] = 10
>>> ibound = np.random.randint(0,2,(3,4))
>>> L1TopOld = np.ones((3,4))*5
>>> h
array([[  0.1382408 ,   0.7718657 ,  10.        ,  10.        ],
       [ 10.        ,   0.5595833 ,   0.83703255,  10.        ],
       [ 10.        ,  10.        ,   0.79473842,   0.91882331]])
>>> ibound
array([[0, 1, 1, 0],
       [0, 1, 1, 0],
       [0, 1, 0, 1]])
>>> L1TopOld
array([[ 5.,  5.,  5.,  5.],
       [ 5.,  5.,  5.,  5.],
       [ 5.,  5.,  5.,  5.]])
>>> eps = 0.01

现在我们可以决定要修补哪些:

^{pr2}$

并使用此命令告诉np.where我们要切换的位置:

>>> np.where(ibound & (abs(h - nodata) <= eps), L1TopOld, h)
array([[  0.1382408 ,   0.7718657 ,   5.        ,  10.        ],
       [ 10.        ,   0.5595833 ,   0.83703255,  10.        ],
       [ 10.        ,   5.        ,   0.79473842,   0.91882331]])

正如评论中指出的,这假设ibound是一个只由0和1组成的掩码。如果你真的只想改变ibound == 1(例如,不是2)的情况,那也很简单:

>>> np.where((ibound == 1) & (abs(h - nodata) <= eps), L1TopOld, h)
array([[  0.1382408 ,   0.7718657 ,   5.        ,  10.        ],
       [ 10.        ,   0.5595833 ,   0.83703255,  10.        ],
       [ 10.        ,   5.        ,   0.79473842,   0.91882331]])

{在这里给出的答案是相同的,因为在cd3中}是相同的

如果要修改原始阵列:

import numpy as np
eps = .01
nodata = 10
h = np.array([[0.1382408, 0.7718657, 10. , 10. ],
              [ 10. , 0.5595833, 0.83703255, 10. ],
              [ 10. , 10. , 0.79473842, 0.91882331]])
h.flat[[2,3,4,7,8,9]] = 10
ibound = np.array([[0, 1, 1, 0],
                   [0, 1, 1, 0],
                   [0, 1, 0, 1]])
L1TopOld = np.array([[ 5., 5., 5., 5.],
                     [ 5., 5., 5., 5.],
                     [ 5., 5., 5., 5.]])

根据您的条件创建逻辑掩码:

^{pr2}$

使用布尔索引修改数组

h[mask] = L1TopOld[mask]
print h

[[  0.1382408    0.7718657    5.          10.        ]
 [ 10.           0.5595833    0.83703255  10.        ]
 [ 10.           5.           0.79473842   0.91882331]]

相关问题 更多 >

    热门问题