计算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。你知道吗
@norok2解决方案的一个稍微高效(但可读性较差)的变体如下所示。你知道吗
可能有一个更有效的解决方案,但是如果您想要显示
test_elements
的“all”元素所在的行,可以反转np.isin
并沿每行应用它,如下所示:创建一个元素的布尔数组,然后按行使用这将避免在同一行中出现多个值,最后使用sum对行进行计数
输出
相关问题 更多 >
编程相关推荐