Tehada - 1 year ago 122
Python Question

I need a fast way to find the smallest element among three neighbor elements in a string, and add it to element under the central element. For border elements only two upper elements are checking.

For example I have a numpy array:

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

I should get this:

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

I have this code:

``````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])
``````

How can I count it without using more
`for`
loops because I have too much data and I need to make it fast?
`Edit:`
David-z, here is my project)

Use `numpy.minimum.reduce`:

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

For example:

``````>>> 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.]])
``````
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download