1

I want to iterate through a numpy ndarray and, if any values are less than X, replace one of them with X.

I have tried doing array_name[ array_name < X] = X but this replaces all of the values that are less than X.

I can use a for loop, but I feel like there's probably a more concise way already bundled with numpy.

        for i in array_name:
            if i < X:
                i = X
                break

Is there a way to do this more elegantly?

1 Answer 1

1
array_name < X

Returns same array but with True or False. Then you can just pick an index where the cell is True

idx = np.argwhere(array_name < X)[i]
array_name[idx] = value

Here, you can choose i arbitrarily

Sign up to request clarification or add additional context in comments.

2 Comments

What are you doing with i there?
Any index in np.argwhere(array_name < X) satisfies your constraint. So i is one of them

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.