对于2D数组,Python中是否有像MATLAB中的“ find”命令一样的命令?
如何在numpy数组中查找行[0.5795946,0.24307856,0.56676058,0.08502582]的位置
A = array([[ 0.57383254, 0.10132767, 0.86211639, 0.35402222],
[ 0.20238346, 0.93204519, 0.84563318, 0.68373515],
[ 0.5795946 , 0.24307856, 0.56676058, 0.08502582],
[ 0.27188428, 0.0630682 , 0.9762359 , 0.50456657],
[ 0.6522969 , 0.85018875, 0.22728716, 0.82851854]])
不使用for循环?
我尝试了以下操作:
for i in range(A.shape[0]):
if (A[i]==[ 0.5795946 , 0.24307856, 0.56676058, 0.08502582]):
print(i)
我遇到以下错误:
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
因此,我想知道是否有更有效或更快速的方法。
答案 0 :(得分:0)
查找数组中元素的索引
import numpy as np
A = np.array([[ 0.57383254, 0.10132767, 0.86211639, 0.35402222],
[ 0.20238346, 0.93204519, 0.84563318, 0.68373515],
[ 0.5795946 , 0.24307856, 0.56676058, 0.08502582],
[ 0.27188428, 0.0630682 , 0.9762359 , 0.50456657],
[ 0.6522969 , 0.85018875, 0.22728716, 0.82851854]])
target = np.array([ 0.57959463 , 0.24307856, 0.56676058, 0.08502582])
np.where(A == target)
输出
(array([2, 2, 2]), array([1, 2, 3]))
返回的第一个数组代表找到该值的行索引,第二个数组代表找到该值的列索引。
找到整个子数组
A = np.array([[ 0.57383254, 0.10132767, 0.86211639, 0.35402222],
[ 0.20238346, 0.93204519, 0.84563318, 0.68373515],
[ 0.5795946 , 0.24307856, 0.56676058, 0.08502582],
[ 0.27188428, 0.0630682 , 0.9762359 , 0.50456657],
[ 0.6522969 , 0.85018875, 0.22728716, 0.82851854]])
target = np.array([ 0.5795946 , 0.24307856, 0.56676058, 0.08502582])
result, = np.where(np.all(A == target, axis=1))
print(result)
输出
[2]
答案 1 :(得分:0)
In [147]: A = np.array([[ 0.57383254, 0.10132767, 0.86211639, 0.35402222],
...: [ 0.20238346, 0.93204519, 0.84563318, 0.68373515],
...: [ 0.5795946 , 0.24307856, 0.56676058, 0.08502582],
...: [ 0.27188428, 0.0630682 , 0.9762359 , 0.50456657],
...: [ 0.6522969 , 0.85018875, 0.22728716, 0.82851854]])
In [148]: target = [ 0.5795946 , 0.24307856, 0.56676058, 0.08502582]
如果比较(5,4)形状A
和target
(4,)形状,则会得到(5,4)布尔数组。当您将目标与行A
进行比较时,结果是4元素数组。您会收到错误消息,因为这样的数组在标量if
上下文中不起作用。
(比较这两个数组时,广播规则适用。要测试列,我们必须使用(5,1)形状目标。)
In [149]: A==target
Out[149]:
array([[False, False, False, False],
[False, False, False, False],
[ True, True, True, True],
[False, False, False, False],
[False, False, False, False]])
==
在这里工作;但更笼统地说,我们想在测试浮点数时使用isclose
:
In [152]: np.isclose(A,target)
Out[152]:
array([[False, False, False, False],
[False, False, False, False],
[ True, True, True, True],
[False, False, False, False],
[False, False, False, False]])
现在我们可以将all
应用于行,以获取True / False数组,每行一个值:
In [153]: np.all(np.isclose(A,target), axis=1)
Out[153]: array([False, False, True, False, False])
以及该行的索引:
In [154]: np.nonzero(np.all(np.isclose(A,target), axis=1))
Out[154]: (array([2]),)