numpy 将数组作为一个整体进行比较
numpy where compare arrays as a whole
我有一个数组 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]))
.我怎样才能得到想要的答案?
可能有点贵但是
x.tolist().index([0,0,0])
应该工作
要适应获取所有匹配索引而不是一个,请使用
xL = x.tolist()
indices = [i for i, x in enumerate(xL) if x == [0,0,0]]
(灵感来自 this answer)
import numpy as np
x = np.array([[0,1,2],[0,0,0],[3,4,0],[1,2,3]])
np.where(np.all(x == [0,0,0], axis=1) == True)[0].tolist()
# outputs [1]
np.all
测试沿 axis=1
的所有元素是否相等,在这种情况下输出 array([False, True, False, False])
。然后使用 np.where
获取符合此条件的索引。
作为@transcranial 解决方案,您可以使用 np.all()
来完成这项工作。但是 np.all()
很慢,所以如果你将它应用到一个大数组,速度将是你关心的问题。
要测试特定值或特定范围,我会这样做。
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()
解决方案的两倍。
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
而且您不仅可以测试相等性,还可以测试范围。
condition = (x[:,0]<3) & (x[:,1]>=1) & (x[:,2]>=0)
np.where(condition)
# (array([0, 3]),)
我有一个数组 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]))
.我怎样才能得到想要的答案?
可能有点贵但是
x.tolist().index([0,0,0])
应该工作
要适应获取所有匹配索引而不是一个,请使用
xL = x.tolist()
indices = [i for i, x in enumerate(xL) if x == [0,0,0]]
(灵感来自 this answer)
import numpy as np
x = np.array([[0,1,2],[0,0,0],[3,4,0],[1,2,3]])
np.where(np.all(x == [0,0,0], axis=1) == True)[0].tolist()
# outputs [1]
np.all
测试沿 axis=1
的所有元素是否相等,在这种情况下输出 array([False, True, False, False])
。然后使用 np.where
获取符合此条件的索引。
作为@transcranial 解决方案,您可以使用 np.all()
来完成这项工作。但是 np.all()
很慢,所以如果你将它应用到一个大数组,速度将是你关心的问题。
要测试特定值或特定范围,我会这样做。
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()
解决方案的两倍。
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
而且您不仅可以测试相等性,还可以测试范围。
condition = (x[:,0]<3) & (x[:,1]>=1) & (x[:,2]>=0)
np.where(condition)
# (array([0, 3]),)