脾气暴躁:高级切片

特哈达

我需要一种快速的方法来查找字符串中三个相邻元素中的最小元素,并将其添加到中心元素下的元素中。对于边界元素,仅检查两个上部元素。

例如,我有一个numpy数组:

    [1, 2, 3, 4, 5], 
    [0, 0, 0, 0, 0]

我应该得到这个:

    [1, 2, 3, 4, 5], 
    [1, 1, 2, 3, 4]

我有以下代码:

for h in range(1, matrix.shape[0]):
    matrix[h][0] = min(matrix[h - 1][0], matrix[h - 1][1])
    matrix[h][1:-1] = ...(DONT KNOW, WHAT SHOULD BE HERE!!)
    matrix[h][-1] = min(matrix[h - 1][-2], matrix[h - 1][-1])

for因为我有太多的数据并且需要使其更快,如何在不使用更多循环的情况下进行计数Edit:David-z,这是我的项目)接缝雕刻

丹尼尔

用途numpy.minimum.reduce

matrix[h][1:-1] = numpy.minimum.reduce([matrix[h-1][0:-2], matrix[h-1][1:-1], matrix[h-1][2:]])

例如:

>>> matrix = numpy.zeros((2,10))
>>> matrix[0, :] = numpy.random.randint(0,100,10)
>>> h = 1
>>> matrix[h][0] = matrix[h-1][:2].min()
>>> matrix[h][1:-1] = numpy.minimum.reduce([matrix[h-1][0:-2], matrix[h-1][1:-1], matrix[h-1][2:]])
>>> matrix[h][-1] = matrix[h-1][-2:].min()
>>> matrix
array([[ 10.,  40.,  90.,  13.,  21.,  58.,  64.,  56.,  34.,  69.],
       [ 10.,  10.,  13.,  13.,  13.,  21.,  56.,  34.,  34.,  34.]])

本文收集自互联网,转载请注明来源。

如有侵权,请联系[email protected] 删除。

编辑于
0

我来说两句

0条评论
登录后参与评论

相关文章