首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Numpy np.where多条件

Numpy np.where多条件
EN

Stack Overflow用户
提问于 2016-09-03 21:08:43
回答 2查看 8.5K关注 0票数 4

我需要使用numpy处理多个条件。

我正在尝试这段似乎可以工作的代码。

我的问题是:有没有另一个替代方案可以做同样的工作?

代码语言:javascript
复制
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']
EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2016-09-04 01:37:49

从这个开始:

代码语言:javascript
复制
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']

试试这个:

代码语言:javascript
复制
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']

这也是可行的:

代码语言:javascript
复制
np.where((Mur<Mu)&(Mu<Mumax),45,np.where(Mu>Mumax,60,np.where(Mu<Mur,0,"zero")))
票数 5
EN

Stack Overflow用户

发布于 2016-09-04 00:55:36

您可以使用Pandas的pd.cut()方法:

生成随机的整数序列:

代码语言:javascript
复制
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

对它们进行分类:

代码语言:javascript
复制
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]
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/39307268

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档