计算2d numpy数组中包含其他1d数组所有元素的所有行的最佳方法?

2024-09-29 17:09:44 发布

您现在位置:Python中文网/ 问答频道 /正文

计算2d numpy数组中包含另一个1d numpy数组的所有值的行的最佳方法是什么?第二个数组的列数可以超过1d数组的长度。你知道吗

elements = np.arange(4).reshape((2, 2))
test_elements = [2, 3]
somefunction(elements, test_elements)

我希望函数返回1。你知道吗

elements = np.arange(15).reshape((5, 3))

# array([[ 0,  1,  2],
#       [ 3,  4,  5],
#       [ 6,  7,  8],
#       [ 9, 10, 11],
#       [12, 13, 14]])

test_elements = [4, 3]
somefunction(elements, test_elements)

也应该返回1。你知道吗

必须包括1d数组的所有元素。如果一行中只找到几个元素,则不算数。因此:

elements = np.arange(15).reshape((5, 3))

# array([[ 0,  1,  2],
#       [ 3,  4,  5],
#       [ 6,  7,  8],
#       [ 9, 10, 11],
#       [12, 13, 14]])

test_elements = [3, 4, 10]
somefunction(elements, test_elements)

还应返回0。你知道吗


Tags: 方法函数testnumpy元素np数组elements
3条回答

@norok2解决方案的一个稍微高效(但可读性较差)的变体如下所示。你知道吗

sum(map(set(test_elements).issubset, elements))

可能有一个更有效的解决方案,但是如果您想要显示test_elements的“all”元素所在的行,可以反转np.isin并沿每行应用它,如下所示:

np.apply_along_axis(lambda x: np.isin(test_elements, x), 1, elements).all(1).sum()

创建一个元素的布尔数组,然后按行使用这将避免在同一行中出现多个值,最后使用sum对行进行计数

np.any(np.isin(elements, test), axis=1).sum()

输出

>>> elements
array([[ 0,  1,  2],
       [ 3,  4,  5],
       [ 6,  7,  8],
       [ 9, 10, 11],
       [12, 13, 14]])
>>> test = [1, 6, 7, 4]
>>> np.any(np.isin(elements, test), axis=1).sum()
3

相关问题 更多 >

    热门问题