5

I need to work with multiple condition using numpy.

I'm trying this code that seem to work.

My question is: There is another alternative that can do the same job?

Mur=np.array([200,246,372])*pq.kN*pq.m
Mumax=np.array([1400,600,700])*pq.kN*pq.m
Mu=np.array([100,500,2000])*pq.kN*pq.m
Acreq=np.where(Mu<Mur,0,"zero")
Acreq=np.where(((Mur<Mu)&(Mu<Mumax)),45,Acreq)
Acreq=np.where(Mu>Mumax,60,Acreq)
Print(Acreq)
['0' '45' '60']
4
  • It's not clear what you are trying to achieve. Can you provide a sample data set and desired data set? In your code pq.kN and pq.m are not defined so it's hard to understand what is your input data set. PS is using Pandas module an option for you? Commented Sep 3, 2016 at 15:57
  • Hi Max, pq.kN and pq.m are units from the package "quantities". I´m trying to make an "if" and "else if" with the conditions: If Mu<Mur ----> "x value" If Mur<Mu<Mumax ----> "y value" If Mu>Mumaz ----> "z value" Commented Sep 3, 2016 at 16:30
  • It can be done pretty easily in Pandas - would it be an option for you? Commented Sep 3, 2016 at 16:37
  • I don´t know what Pandas is. I´m a newbie in Python. But, yes, I have no problem trying this option. Commented Sep 3, 2016 at 16:43

2 Answers 2

5

Starting with this:

Mur    = np.array([200,246,372])*3*5
Mumax  = np.array([1400,600,700])*3*5
Mu     = np.array([100,500,2000])*3*5
Acreq  = np.where(Mu<Mur,0,"zero")
Acreq  = np.where((Mur<Mu)&(Mu<Mumax),45,Acreq)
Acreq  = np.where(Mu>Mumax,60,Acreq)

print(Acreq)

['0' '45' '60']

Try this:

conditions  = [Mu<Mur, (Mur<Mu)&(Mu<Mumax), Mu>Mumax ]
choices     = [ 0, 45, 60 ]
Acreq       = np.select(conditions, choices, default='zero')
print(Acreq)


['0' '45' '60']

This also works:

np.where((Mur<Mu)&(Mu<Mumax),45,np.where(Mu>Mumax,60,np.where(Mu<Mur,0,"zero")))
Sign up to request clarification or add additional context in comments.

4 Comments

Excellent! Thank You!
Looks promising. How about with something like : Mur,Mumax,Mu = [53,39,50]?
If you use Mur,Mumax,Mu = [53,39,50] as the inputs and try out the original code and then your code, they give different results.
Mur,Mumax,Mu = [53,39,50] returns 60 in OP and both versions of the answered code.
2

you can use Pandas's pd.cut() method:

generate random series of integers:

In [162]: import pandas as pd

In [163]: s = pd.Series(np.random.randint(-3,10, 10))

In [164]: s
Out[164]:
0    6
1   -3
2    6
3    6
4    7
5    7
6    3
7   -2
8    9
9    1
dtype: int32

categorize them:

In [165]: pd.cut(s, bins=[-np.inf, 2, 5, np.inf], labels=['0', '45', '60'])
Out[165]:
0    60
1     0
2    60
3    60
4    60
5    60
6    45
7     0
8    60
9     0
dtype: category
Categories (3, object): [0 < 45 < 60]

1 Comment

Thanks! I´ll try this method

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.