如何找到嵌套在另一个数组中的数组的索引?

3

我正在尝试找到在另一个数组中获取嵌套数组索引的最有效方法。

import numpy as np
#                     0     1      2     3
haystack = np.array([[1,3],[3,4,],[5,6],[7,8]])
needles  = np.array([[3,4],[7,8]])

给定包含在needles中的数组,我想要找到它们在haystack中的索引。在这种情况下是1,3。

我想出了以下解决方案:

 indexes = [idx for idx,elem in enumerate(haystack) if elem in needles ]

这是错误的,因为实际上只需要在elem中有一个元素在needles中即可返回idx

是否有更快的替代方案?


索引 = [idx for idx, elem in enumerate(needles) if elem in haystack]这会获取针在干草堆中的索引,而不是干草堆中的索引! - h4z3
2个回答

0

这个响应提供了一个类似问题的解决方案获取两个2D numpy数组中相交的行, 你可以使用np.in1d函数,它非常高效,但是你需要给它提供两个数组的视图,以便将它们处理为1d数据数组。 在你的情况下,你可以这样做:

A = np.array([[1,3],[3,4,],[5,6],[7,8]])
B = np.array([[3,4],[7,8]])
nrows, ncols = A.shape
dtype={'names':['f{}'.format(i) for i in range(ncols)],
       'formats':ncols * [A.dtype]}
indexes, = np.where(np.in1d(A.view(dtype), B.view(dtype)))

它输出:

print(indexes)
> array([1, 3])

0
你可以试试这个。
indices = np.apply_along_axis(lambda x: np.where(np.isin(haystack, x).sum(axis=1)==2)[0], 1, needles).flatten()
indices
>>> array([1, 3])

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接