1

I have an numpy array of numbers x and some thresholds [A,B,C,D]

I want to apply 5 different formulas to each of the slices of the array, but ideally I don't want to iterate over it (that's why I'm trying to use numpy).

What's the best way to do it? This is what I'm trying to do, is there a better way?

cond_A = np.where(x <= A)
cond_B = np.where((x > A) & (x <= B))
cond_C = np.where((x > B) & (x <= C))
cond_D = np.where((x > C) & (x <= D))
cond_E =np.where(x > D)

x[cond_A] = function_A(x[cond_A])
...
...
x[cond_E]= function_E(x[cond_E])

EDIT: If I try this I'm getting the error:

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

2 Answers 2

2

You have to use the intersect1d function from numpy in order to apply multiple filters. Here are one example with output in comments, hope this helps

import numpy as np

def function(x):
    return x+10

a = np.arange(10)
print(a) # [0 1 2 3 4 5 6 7 8 9]

mask = np.intersect1d(np.where(a>3), np.where(a<6))
a[mask] = function(a[mask])
print(a) # [ 0  1  2  3 14 15  6  7  8  9]
Sign up to request clarification or add additional context in comments.

Comments

0

& is the bitwise and operator, I assume you're using and since that's when your reported error happens.

If you want to manipulate arrays in this manner, functional programming concepts like map and filter or list comprehensions will help you. Other answer used numpy functions, here's an answer using list comprehensions:

x = [function_A(i) if cond_A else i for i in myarray]

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.