【问题标题】:Numpy np.where multiple conditionNumpy np.where 多个条件
【发布时间】:2016-09-03 13:08:42
【问题描述】:

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

我正在尝试这个似乎有效的代码。

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

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

【问题讨论】:

  • 不清楚您要达到的目标。你能提供一个样本数据集和所需的数据集吗?在您的代码中 pq.kNpq.m 没有定义,因此很难理解您的输入数据集是什么。 PS 是否可以选择使用 Pandas 模块?
  • Hi Max、pq.kN 和 pq.m 是“数量”包中的单位。我正在尝试使用以下条件制作“if”和“else if”: If Mu "x value" If Mur "y value" If Mu> Mumaz ----> "z 值"
  • 在 Pandas 中可以很容易地完成 - 你会选择它吗?
  • 我不知道 Pandas 是什么。我是 Python 的新手。但是,是的,我尝试这个选项没有问题。

标签: python numpy where


【解决方案1】:

从这里开始:

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")))

【讨论】:

  • 太棒了!谢谢!
  • 看起来很有希望。像这样的东西怎么样:Mur,Mumax,Mu = [53,39,50]
  • 如果您使用Mur,Mumax,Mu = [53,39,50] 作为输入并尝试原始代码然后您的代码,它们会给出不同的结果。
  • Mur,Mumax,Mu = [53,39,50] 在 OP 和两个版本的已回答代码中返回 60。
【解决方案2】:

你可以使用 Pandas 的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]

【讨论】:

  • 谢谢!我会试试这个方法
猜你喜欢
  • 2022-06-13
  • 2020-04-02
  • 2017-02-02
  • 1970-01-01
  • 1970-01-01
  • 2016-08-04
  • 2021-12-18
  • 2017-11-18
  • 2021-09-17
相关资源
最近更新 更多