比较两个数组并打印出 python 中行的索引

Compare two arrays and print out Index of row in python

我有两个数组 A 和 B

A = np.array([[9, 10, 11, 12.0],[13 14 15 16.3]])
B = np.array([[1, 2, 3, 4],[5, 6, 7, 8],[9, 10, 11, 12],[13, 14, 15, 16],[17, 18, 19, 20]])

我想比较 A[:,2:4] 的几个元素和 B[:,2:4] 的几个元素并打印出它们相等或近似的行? 这是我的方法,仅适用于 A[:,3]

import math
import cmath
import numpy as np
A = np.array([[9, 10, 11, 12],[13, 14, 15, 16.3]])
B = np.array([[1, 2, 3, 4],[5, 6, 7, 8],[9, 10, 11, 12],[13, 14, 15, 16],[17, 18, 19, 20]])
for k in range(0,A.shape[0]):
    i = np.where(np.isclose(B[:,3], A[k,3], atol=0.5))
    print (i)

如何同时使用 A[:,2]A[:,3]

非常感谢

我想你正在寻找这样的东西:

import numpy as np

indexes_to_compare = range(2,4)
A = np.array([[9, 10, 11, 12],[13, 14, 15, 16.3]])
B = np.array([[1, 2, 3, 4],[5, 6, 7, 8],[9, 10, 11, 12],[13, 14, 15, 16],[17, 18, 19, 20]])

for a in A:
    print(np.where(np.all(np.isclose(B[:,indexes_to_compare], a[indexes_to_compare], atol=0.5), axis=1))[0])

您将 BA 的每一行进行比较,仅考虑少数索引。

因此你:

  • 检查 B 是否接近具有 np.isclose(_)
  • A 行(在选定的索引中)
  • 只保留所有个选定索引接近的行,np.all(_, axis=1)
  • 使用 np.where
  • 获取此类行的索引

如果你想确保每个循环只输出一行B,只需使用np.where(_)[0][0]