【问题标题】:Numpy array comparison using nditer使用 nditer 进行 Numpy 数组比较
【发布时间】:2013-05-09 05:33:49
【问题描述】:

下面的代码给出了正确的答案,但仅在数组(planmeas)相对较小时才有效。当我尝试在我实际需要比较的数组上运行它时(每个 300x300),它需要很长时间(我不知道多长时间,因为我在 45 分钟后终止了它。)我只想迭代一个范围正在评估的索引周围的数组值 (p)。我试图找到有关 nditer 标志 'ranged' 的文档,但找不到如何实现特定范围以进行迭代。

p = np.nditer(plan, flags = ['multi_index','common_dtype'])
while not p.finished:
    gam_store = 100.0
    m = np.nditer(meas, flags = ['multi_index','common_dtype'])
    while not m.finished:
        dis_eval = np.sqrt(np.absolute(p.multi_index[0]-m.multi_index[0])**2 + np.absolute(p.multi_index[1]-m.multi_index[1])**2)           
        if dis_eval <= 6.0:
            a = (np.absolute(p[0] - m[0]) / maxdose) **2
            b = (dis_eval / gam_dist) **2
            gam_eval = np.sqrt(a + b)
            if gam_eval < gam_store:
                gam_store = gam_eval
        m.iternext()    
    gamma = np.insert(gamma, location, gam_store, 0)
    location = location + 1
    p.iternext()

【问题讨论】:

  • 您是否使用np.insert 将值添加到数组的末尾?如果是这样,您应该使用np.append。它将比np.insert 更优化。这可能会有所帮助。
  • 也许我误解了这个问题。如果您只想遍历数组的一部分,为什么不直接切片呢?如果没有,你想用'ranged'做什么?
  • 切片是个好主意。我想多了这个问题。我会努力的。
  • @blake,我会在创建 nditer 之前尝试切片,例如:p = np.nditer(plan[a:b], ...) 另外,如果您想引起某人的注意,请包括他们的用户名:@blake。
  • @askwechan 如果我有一个 2D numpy 数组,我如何分割一个 2d 区域,例如围绕索引值的 10x10 数组?

标签: python arrays numpy iteration


【解决方案1】:

如果您只想遍历数组的一小部分,我认为(除非我误解了这个问题)您应该只从数组的一部分创建一个 nditer 实例。

假设你只想要(i,j)附近的数组,那么就从这个开始:

w = 5    # half-size of the window around i, j
p = np.nditer(plan[i-w:i+w, j-w:j+w], flags=...)

这行得通,因为,说

a = array([[ 0,  1,  2,  3,  4],
           [ 5,  6,  7,  8,  9],
           [10, 11, 12, 13, 14],
           [15, 16, 17, 18, 19],
           [20, 21, 22, 23, 24]])

那么,

w = 1
i, j = 2,2
print a[i-w:i+w+1, j-w:j+w+1]
#array([[ 6,  7,  8],
#       [11, 12, 13],
#       [16, 17, 18]])

【讨论】:

  • 谢谢,帮了大忙。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-11-21
  • 2022-01-23
  • 2017-02-07
  • 2018-12-03
  • 1970-01-01
  • 2021-06-24
相关资源
最近更新 更多