1

Is there anyway to basically take a column of a numpy array and whenever the absolute value is greater than a number, set the value to that signed number.

ie.

for val in col:
    if abs(val) > max:
        val = (signed) max

I know this can be done by looping and such but i was wondering if there was a cleaner/builtin way to do this.

I see there is something like

arr[arr > 255] = x

Which is kind of what i want but i want do this by column instead of the whole array. As a bonus maybe a way to do absolute values instead of having to do two separate operations for positive and negative.

3 Answers 3

5

The other answer is good but it doesn't get you all the way there. Frankly, this is somewhat of a RTFM situation. But you'd be forgiven for not grokking the Numpy indexing docs on your first try, because they are dense and the data model will be alien if you are coming from a more traditional programming environment.

You will have to use np.clip on the columns you want to clip, like so:

x[:,2] = np.clip(x[:,2], 0, 255)

This applies np.clip to the 2nd column of the array, "slicing" down all rows, then reassigns it to the 2nd column. The : is Python syntax meaning "give me all elements of an indexable sequence".

More generally, you can use the boolean subsetting index that you discovered in the same fashion, by slicing across rows and selecting the desired columns:

x[x[:,2] > 255, 2] = -1
Sign up to request clarification or add additional context in comments.

Comments

1

Try calling clip on your numpy array:

import numpy as np
values = np.array([-3,-2,-1,0,1,2,3])
values.clip(-2,2)

Out[292]:
array([-2, -2, -1,  0,  1,  2,  2])

Comments

0

Maybe is a little late, but I think it's a good option:

import numpy as np

values = np.array([-3,-2,-1,0,1,2,3])
values = np.clip(values,-2,2)

Comments

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.