0

I have a 3 dimensional uint8 numpy array. I want to increase all the elements by 1 which has these values: 0,1,3,16,17,18. And set others to 0. I have tried using traditional for loops which is really really slow.

Tried using python indexing techniques to set other values to 255 (which will later be changed to 0)

mask[(mask[:,:,:] != 0) & (mask[:,:,:] != 1) & (mask[:,:,:] != 3) & (mask[:,:,:] != 16) & (mask[:,:,:] != 17) & (mask[:,:,:] != 18)] = 255

Then increasing the values by 1

mask[(mask[:,:,:] == 0) & (mask[:,:,:] == 1) & (mask[:,:,:] == 3) & (mask[:,:,:] == 16) & (mask[:,:,:] == 17) & (mask[:,:,:] == 18)] = mask[:,:,:]+1 #gives me error

Then changing the 255 to 0

mask[mask[:,:,:] == 255] = 0

The middle operation gives me error

ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()

How to do that efficiently. Preferably in one go. Not 3 times iterating the array.

1 Answer 1

3

Use np.isin and then boolean indexing to change values as:

arr = np.arange(0,255)
mask = np.isin(arr,[0,1,3,16,17,18])

arr[mask]+=1
arr[~mask]=0

Or use np.where as:

arr = np.where(np.isin(arr,[0,1,3,16,17,18]),arr+1,0)

arr
array([ 1,  2,  0,  4,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0, 17,
       18, 19,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,
        0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,
        0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,
        0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,
        0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,
        0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,
        0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,
        0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,
        0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,
        0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,
        0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,
        0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,
        0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,
        0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0])
Sign up to request clarification or add additional context in comments.

2 Comments

That's just marvelous! I was converting and writing the arrays to disk like 50 arrays per seconds using traditional for loop. Now its more like 500 per seconds or more!
@Tahlil Numpy array methods are always fast. We need to know how to use it and where to use it properly.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.