1

For example, I have an array X = np.array([1,-3,5,0,9,12])

I wanna make a function a like this.

def bigfunction(X)
    if X<0:
        return 99
    if X=>0 and X<=10
        return 100
    if X>10
        return 101

Which return also an array. In this case [100,99,100,100,100,101] Obviously, this code will not work. It is very import that I can't do it in a loop. I am wondering that if there has implemented the code in numpy solve this problem.

2 Answers 2

2

You can try np.select:

conds = [X < 0, X <= 10]

choices = [99, 100]

np.select(conds, choices, default=101)

This will return:

array([100,  99, 100, 100, 100, 101])
Sign up to request clarification or add additional context in comments.

Comments

2
Y = np.zeros(X.shape, dtype=int)
Y[X<0] = 99
Y[(X>= 0) & (X<10)] = 100
Y[X>10] = 101

Where Y will be your returned array.

1 Comment

You can also use np.zeros_like(X, dtype=np.int)

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.