gpt4 book ai didi

python - 检查两个 2D numpy 数组的公共(public)元素,无论是行还是列

转载 作者:太空宇宙 更新时间:2023-11-04 00:42:35 25 4
gpt4 key购买 nike

给定 nx3mx3 的两个 numpy 数组,确定行索引(计数器)的有效方法是什么?常见于两个数组。例如,我有以下解决方案,对于更大的阵列来说速度非常慢

def arrangment(arr1,arr2):
hits = []
for i in range(arr2.shape[0]):
current_row = np.repeat(arr2[i,:][None,:],arr1.shape[0],axis=0)
x = current_row - arr1
for j in range(arr1.shape[0]):
if np.isclose(x[j,0],0.0) and np.isclose(x[j,1],0.0) and np.isclose(x[j,2],0.0):
hits.append(j)

return hits

它检查 arr2 的行是否存在于 arr1 中,并返回行匹配的 arr1 的行索引。我需要这种安排始终按 arr2 的行顺序递增。例如给定

arr1 = np.array([[-1., -1., -1.],
[ 1., -1., -1.],
[ 1., 1., -1.],
[-1., 1., -1.],
[-1., -1., 1.],
[ 1., -1., 1.],
[ 1., 1., 1.],
[-1., 1., 1.]])
arr2 = np.array([[-1., 1., -1.],
[ 1., 1., -1.],
[ 1., 1., 1.],
[-1., 1., 1.]])

函数应该返回:

[3, 2, 6, 7]

最佳答案

快速而肮脏的回答

(arr1[:, None] == arr2).all(-1).argmax(0)

array([3, 2, 6, 7])

更好的答案
处理 arr2 中的一行与 arr1

中的任何内容不匹配的机会
t = (arr1[:, None] == arr2).all(-1)
np.where(t.any(0), t.argmax(0), np.nan)

array([ 3., 2., 6., 7.])

正如@Divakar 所指出的,np.isclose 解释了比较 float 时的舍入误差

t = np.isclose(arr1[:, None], arr2).all(-1)
np.where(t.any(0), t.argmax(0), np.nan)

关于python - 检查两个 2D numpy 数组的公共(public)元素,无论是行还是列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41234161/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com