2

I want to replace a numpy array values with a counter, if they meet a condition.

'Arr' is a NxM numpy array. I would like 'ArrCount' (NxM) to have values from i=1 to i=n, if the value in 'Arr' doesn't equal 65535. for large arrays, iterating over each cell takes a long time.

import numpy as np
ArrCount= np.empty_like(Arr)
    i = 1
    for index, x in np.ndenumerate(Arr):
        if x!= 65535:
            ArrCount[index] = i
            i += 1

I've also tries working with mask and Boolean arrays, but this doesn't improve the iterating time. Is there a better way of doing this?

1
  • 3
    Sorry it isn't clear to me exactly what you want to do. Can you supply an example input and expected output? Commented Sep 3, 2019 at 12:03

1 Answer 1

2

Try to avoid for-loops at all when you use Numpy. Here is a vectorized approach to do something like that:

import numpy as np

a = np.random.rand(10)

# boolean array, other operators also work (>=, ==, <=)
is_larger = a > 0.5

# how many elements fit the criteria?
count = np.count_nonzero(is_larger)

# create an ascending array that long
asc = np.arange(count)

# boolean indexing to assign the values to the correct places
a[is_larger] = asc

print(a)
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks This works great in a much more efficient way. i knew i needed to avoid looping just didn't know how.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.