numpy比较整个数组 [英] numpy where compare arrays as a whole

查看:138
本文介绍了numpy比较整个数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个数组x=np.array([[0,1,2,],[0,0,0],[3,4,0],[1,2,3]]),我想获取x = [0,0,0]的索引,即1.我尝试了np.where(x==[0,0,0])生成了(array([0, 1, 1, 1, 2]), array([0, 0, 1, 2, 2])).如何获得所需的答案?

I have an array x=np.array([[0,1,2,],[0,0,0],[3,4,0],[1,2,3]]), and I want to get the index where x=[0,0,0], i.e. 1. I tried np.where(x==[0,0,0]) resulting in (array([0, 1, 1, 1, 2]), array([0, 0, 1, 2, 2])). How can I get the desired answer?

推荐答案

作为@transcranial解决方案,您可以使用np.all()来完成这项工作.但是np.all()速度很慢,因此如果将其应用于大型阵列,速度将是您的关注点.

As @transcranial solution, you can use np.all() to do the job. But np.all() is slow, so if you apply it to a large array, speed will be your concern.

要测试特定值或特定范围,我会这样做.

To test for a specific value or a specific range, I would do like this.

x = np.array([[0,1,2],[0,0,0],[3,4,0],[1,2,3],[0,0,0]])

condition = (x[:,0]==0) & (x[:,1]==0) & (x[:,2]==0)
np.where(condition)
# (array([1, 4]),)

这有点丑陋,但速度几乎是np.all()解决方案的两倍.

It's a bit ugly but it almost twice as fast as np.all() solution.

In[23]: %timeit np.where(np.all(x == [0,0,0], axis=1) == True)
100000 loops, best of 3: 6.5 µs per loop
In[22]: %timeit np.where((x[:,0]==0)&(x[:,1]==0)&(x[:,2]==0))
100000 loops, best of 3: 3.57 µs per loop

您不仅可以测试相等性,还可以测试范围.

And you can test not only for equality but also a range.

condition = (x[:,0]<3) & (x[:,1]>=1) & (x[:,2]>=0)
np.where(condition)
# (array([0, 3]),)

这篇关于numpy比较整个数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆