Home > other >  If statement with multiple conditions using two arrays - python
If statement with multiple conditions using two arrays - python

Time:07-20

I'm having trouble constructing an if statement that applies multiple conditions with two arrays.

I would like to check two conditions whereby if the answer is True to either of these conditions then the first formula will be used otherwise the second formula will be used. I would like to do this cycling through 2 arrays and storing the values as I go.

The error I get is:

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

Is the following the correct method to implement this or am I way off and should be using a for loop to go through the arrays?

u2 = [0.01, 0.04, 0.07, 0.04]
Bq = [10, 15, 25, 21]
Qp = [1, 2, 1, 2]
k1 = 2
k2 = 1   
    
if (u2 < 0.02 or Bq < 20):
            a = -np.log(Qp-Qp*Bq 1)/k1
        else:
            a = -np.log(Qp-Qp*Bq 1)/k2

Any help would be greatly appreciated.

Apologies I tried to simplify my code and ended up making it more confusing.

CodePudding user response:

You need to iterate over both lists to check each and every value, you can't do it as a single expression.

You can use the zip functions to iterate over the two lists simultaneously:

for (u, b) in zip(u2, Bq):
    if u < 0.02 or b < 20:
        # TODO: Do something
    else:
        # TODO: Do something else

CodePudding user response:

Well you could technically use logical indexing to solve it. I didn't check in detail if it is fully functional, but you could use something like this, since you are already using numpy:

import numpy as np
u2 = np.array([0.01, 0.04, 0.07, 0.04])
Bq = np.array([10, 15, 25, 21])
Qp = np.array([1, 2, 1, 2])
k1 = 2
k2 = 1   
logical_array=np.logical_or(u2 < 0.02,Bq < 20)
results=np.zeros(4)
results[logical_array]=-np.log(Qp[logical_array]-Qp[logical_array]*Bq[logical_array] 1)/k1
results[~logical_array]=-np.log(Qp[~logical_array]-Qp[~logical_array]*Bq[~logical_array] 1)/k2

Edit: I don't know what is going on in your formula, but it results in negative values for the logarithm. Be careful.

  • Related