我需要一种快速的方法来找到字符串中三个相邻元素中的最小元素,并将其添加到中心元素下的元素中。对于边框元素,只有两个上部元素正在检查。
例如我有一个 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
循环的情况下对其进行计数? 编辑:
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.]])
关于python - Numpy:高级切片,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39064607/