如何在给定条件下选择数组的元素?
- 2025-03-18 08:56:00
- admin 原创
- 52
问题描述:
假设我有一个numpy数组x = [5, 2, 3, 1, 4, 5]
,y = ['f', 'o', 'o', 'b', 'a', 'r']
。我想选择y
对应于中x
大于1且小于5的元素的元素。
我试过
x = array([5, 2, 3, 1, 4, 5])
y = array(['f','o','o','b','a','r'])
output = y[x > 1 & x < 5] # desired output is ['o','o','a']
但这不起作用。我该怎么做?
解决方案 1:
如果添加括号,您的表达式就会有效:
>>> y[(1 < x) & (x < 5)]
array(['o', 'o', 'a'],
dtype='|S1')
解决方案 2:
在我看来,OP 实际上并不想要np.bitwise_and()
(又名&
),但实际上想要np.logical_and()
,因为他们正在比较逻辑值,例如True
和- 请参阅有关逻辑与按位的False
SO 帖子以查看差异。
>>> x = array([5, 2, 3, 1, 4, 5])
>>> y = array(['f','o','o','b','a','r'])
>>> output = y[np.logical_and(x > 1, x < 5)] # desired output is ['o','o','a']
>>> output
array(['o', 'o', 'a'],
dtype='|S1')
而等效的方法是np.all()
通过适当设置axis
参数。
>>> output = y[np.all([x > 1, x < 5], axis=0)] # desired output is ['o','o','a']
>>> output
array(['o', 'o', 'a'],
dtype='|S1')
从数字上看:
>>> %timeit (a < b) & (b < c)
The slowest run took 32.97 times longer than the fastest. This could mean that an intermediate result is being cached.
100000 loops, best of 3: 1.15 µs per loop
>>> %timeit np.logical_and(a < b, b < c)
The slowest run took 32.59 times longer than the fastest. This could mean that an intermediate result is being cached.
1000000 loops, best of 3: 1.17 µs per loop
>>> %timeit np.all([a < b, b < c], 0)
The slowest run took 67.47 times longer than the fastest. This could mean that an intermediate result is being cached.
100000 loops, best of 3: 5.06 µs per loop
因此使用np.all()
较慢,但&
和logical_and
大致相同。
解决方案 3:
在@JF Sebastian 和@Mark Mikofski 的答案中添加一个细节:
如果想要获取相应的索引(而不是数组的实际值),则可以执行以下代码:
为了满足多个(所有)条件:
select_indices = np.where( np.logical_and( x > 1, x < 5) )[0] # 1 < x <5
为了满足多个(或)条件:
select_indices = np.where( np.logical_or( x < 1, x > 5 ) )[0] # x <1 or x >5
解决方案 4:
我喜欢用它np.vectorize
完成这样的任务。考虑以下几点:
>>> # Arrays
>>> x = np.array([5, 2, 3, 1, 4, 5])
>>> y = np.array(['f','o','o','b','a','r'])
>>> # Function containing the constraints
>>> func = np.vectorize(lambda t: t>1 and t<5)
>>> # Call function on x
>>> y[func(x)]
>>> array(['o', 'o', 'a'], dtype='<U1')
优点是您可以在矢量化函数中添加更多类型的约束。
希望有帮助。
解决方案 5:
实际上我会这样做:
L1是满足条件1的元素的索引列表;(也许您可以使用somelist.index(condition1)
或np.where(condition1)
来获取L1。)
类似地,你得到 L2,即满足条件 2 的元素列表;
然后使用 找到交点intersect(L1,L2)
。
如果满足多个条件,您还可以找到多个列表的交集。
然后您可以在任何其他数组中应用索引,例如 x。
解决方案 6:
对于 2D 数组,您可以这样做。使用条件创建 2D 掩码。根据数组将条件掩码类型转换为 int 或 float,然后将其与原始数组相乘。
In [8]: arr
Out[8]:
array([[ 1., 2., 3., 4., 5.],
[ 6., 7., 8., 9., 10.]])
In [9]: arr*(arr % 2 == 0).astype(np.int)
Out[9]:
array([[ 0., 2., 0., 4., 0.],
[ 6., 0., 8., 0., 10.]])
相关推荐
热门文章
项目管理软件有哪些?
热门标签
曾咪二维码
扫码咨询,免费领取项目管理大礼包!
云禅道AD