我是Python的新手,我的问题似乎很糟糕地解释了,因为我有MATLAB的背景。通常在MATLAB中,如果我们有1000个阵列为15*15,则定义一个单元格或一个3D矩阵,每个元素是大小(15*15(的矩阵。
现在在Python中:(使用numpy库(我有一个形状的ndarray a(1000,15,15(。我还有另一个具有形状的ndarry b(500,15,15(。
我也试图在B中找到A中的成员中的元素。我特别正在寻找可以返回的向量,并在B中找到的元素索引。
通常在matlab中,我将它们重塑以制作2D数组(1000*225(和(500*225(,并使用'ismember'函数,通过"行"参数来查找并返回相似行的索引。
Numpy(或任何其他库(中是否有类似的功能可以执行此操作?我正在尝试进行循环。
谢谢
这是使用views
的一种方法,主要基于this post
-
# Based on https://stackoverflow.com/a/41417343/3293881 by @Eric
def get_index_matching_elems(a, b):
# check that casting to void will create equal size elements
assert a.shape[1:] == b.shape[1:]
assert a.dtype == b.dtype
# compute dtypes
void_dt = np.dtype((np.void, a.dtype.itemsize * np.prod(a.shape[1:])))
# convert to 1d void arrays
a = np.ascontiguousarray(a)
b = np.ascontiguousarray(b)
a_void = a.reshape(a.shape[0], -1).view(void_dt)
b_void = b.reshape(b.shape[0], -1).view(void_dt)
# Get indices in a that are also in b
return np.flatnonzero(np.in1d(a_void, b_void))
样本运行 -
In [87]: # Generate a random array, a
...: a = np.random.randint(11,99,(8,3,4))
...:
...: # Generate random array, b and set few of them same as in a
...: b = np.random.randint(11,99,(6,3,4))
...: b[[0,2,4]] = a[[3,6,1]]
...:
In [88]: get_index_matching_elems(a,b)
Out[88]: array([1, 3, 6])