2016-09-03 20 views
2

我需要使用numpy使用多个条件。numpy np.其中多个条件

我想这个代码,似乎工作。

我的问题是:还有另一种可以做同样工作的方法吗?

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'] 
+0

目前尚不清楚你想要达到的目的。你能提供一个样本数据集和所需的数据集吗?在你的代码中'pq.kN'和'pq.m'没有被定义,所以很难理解你的输入数据集是什么。 PS是否使用Pandas模块作为选项? – MaxU

+0

Hi Max,pq.kN和pq.m是包装“数量”中的单位。我试图用以下条件制作一个“if”和“else if”: 如果Mu如果Mu> Mumaz ---->“z值”如果Mu “y值” “ – Eduardo

+0

熊猫可以很容易地完成它 - 它会成为你的选择吗? – MaxU

回答

3

与此开始:

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'] 

试试这个:

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'] 

这也适用于:

np.where((Mur<Mu)&(Mu<Mumax),45,np.where(Mu>Mumax,60,np.where(Mu<Mur,0,"zero"))) 
+0

优秀!谢谢! – Eduardo

+0

看起来很有希望。如何处理:Mur,Mumax,Mu = [53,39,50]'? – Divakar

+0

如果你使用'Mur,Mumax,Mu = [53,39,50]'作为输入并且尝试原始代码,然后尝试你的代码,他们会给出不同的结果。 – Divakar

1

可以使用熊猫的pd.cut()方法:

生成随机整数系列:

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 

他们分类:

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] 
+0

谢谢!我会尝试这种方法 – Eduardo