简体   繁体   中英

Replacing specific values of a 2d numpy array, but only at the edges

To illustrate my point, lets take this 2d numpy array:

array([[1, 1, 5, 1, 1, 5, 4, 1],
       [1, 5, 6, 1, 5, 4, 1, 1],
       [5, 1, 5, 6, 1, 1, 1, 1]])

I want to replace the value 1 with some other value, let's say 0, but only at the edges. This is the desired result:

array([[0, 0, 5, 1, 1, 5, 4, 0],
       [0, 5, 6, 1, 5, 4, 0, 0],
       [5, 1, 5, 6, 0, 0, 0, 0]])

Note that the 1's surrounded by other values are not changed.

I could implement this by iterating over every row and element, but I feel like that would be very inefficient. Normally I would use the np.where function to replace a specific value, but I don't think you can add positional conditions?

m = row!=1   
w1 = m.argmax()-1
w2 = m.size - m[::-1].argmax()

These three lines will give you the index for the trailling ones. The idea has been taken from trailing zeroes.

Try:

arr = np.array([[1, 1, 5, 1, 1, 5, 4, 1],
       [1, 5, 6, 1, 5, 4, 1, 1],
       [5, 1, 5, 6, 1, 1, 1, 1]])

for row in arr:
    m = row!=1

    w1 = m.argmax()-1
    w2 = m.size - m[::-1].argmax()
#     print(w1, w2)
    row[0:w1+1] = 0
    row[w2:] = 0
#     print(row)

arr:

array([[0, 0, 5, 1, 1, 5, 4, 0],
       [0, 5, 6, 1, 5, 4, 0, 0],
       [5, 1, 5, 6, 0, 0, 0, 0]])

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM