数组比较的数字方式?

2024-09-30 20:37:52 发布

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

考虑到以下代码:

>>> initial_array = np.vstack(([0, 1, 2, 3, 4, 11, 6, 7, 8, 9], [1, 11, 12, 13, 14, 15, 16, 17, 18, 19])).T
>>> initial_array
array([[ 0,  1],
       [ 1, 11],
       [ 2, 12],
       [ 3, 13],
       [ 4, 14],
       [11, 15],
       [ 6, 16],
       [ 7, 17],
       [ 8, 18],
       [ 9, 19]])

>>> test = np.vstack(([0, 1, 2, 67, 4, 5], [10, 11, 67, 13, 14, 67])).T
>>> test
array([[ 0, 10],
       [ 1, 11],
       [ 2, 67],
       [67, 13],
       [ 4, 14],
       [ 5, 67]])

有没有一种比较initial_arrayw.r.ttest的每一行的方法来得到如下掩码?你知道吗

[False, True, False, False, True, False, False, False, False, False]

其思想是要知道initial_array的哪些行(对)包含在test中。你知道吗

提前谢谢。你知道吗


Tags: 方法代码testfalsetruenparrayinitial
3条回答

您可以使用广播在两个数组中的每个数组中的所有对之间进行比较,然后使用np.anynp.all将结果合并到所需的一维数组中作为结果:

result = np.any(np.all(initial_array[:,None] == test[None,:], axis=2), axis=1)

您可以尝试利用unique()函数。你知道吗

  1. 合并测试和初始数组
  2. 计算唯一行,从唯一行到原始数组的逆映射,以及合并数组中给定唯一行的第一次出现。 功能np.唯一做所有这些工作。你知道吗
  3. 通过检查第一个值是否出现在第一个len(test)行之后,检查哪些唯一值仅出现在初始\u数组中。你知道吗
  4. 使用逆映射为最后一列(初始数组)行重建布尔数组

代码:

import numpy as np

initial_array = np.vstack(([0, 1, 2, 3, 4, 11, 6, 7, 8, 9], [1, 11, 12, 13, 14, 15, 16, 17, 18, 19])).T
test = np.vstack(([0, 1, 2, 67, 4, 5], [10, 11, 67, 13, 14, 67])).T

merged = np.vstack((test, initial_array))

_, index, inverse = np.unique(merged, return_index=True, return_inverse=True, axis=0)

mask = index < len(test)

result = mask[inverse[len(test):]]

print(result)

稍微简单一点的解决方案是使用合并数组上的unique()为每个唯一的行分配一个唯一的整数。接下来,使用numpy中可用的1D set操作(function in1d())完成比较

merged = np.vstack((test, initial_array))
_, uniqinv = np.unique(merged, return_inverse=True, axis=0)
result = np.in1d(uniqinv[len(test):], uniqinv[:len(test)])
print(result)

此解决方案的缺点是执行两种排序(unique()和in1d())。你知道吗

这里有一种方法:

res = []
# Go through all your array pairs
for ar in initial_array:
    found = False

    # Compare against all other pairs in test 
    for tes in test:
        # Make sure arrays are exactly the same
        if (ar==tes).all():
            res.append(True)
            found = True
            break

    # False if you didn't find a match
    if found:
        continue
    res.append(False)

print(res)
[False, True, False, False, True, False, False, False, False, False]

相关问题 更多 >