gpt4 book ai didi

python - 测试二维 numpy 数组中的成员资格

转载 作者:太空狗 更新时间:2023-10-29 18:24:32 26 4
gpt4 key购买 nike

我有两个相同大小的二维数组

a = array([[1,2],[3,4],[5,6]])
b = array([[1,2],[3,4],[7,8]])

我想知道 b 在 a 中的行。

所以输出应该是:

array([ True,  True, False], dtype=bool)

没有制作:

array([any(i == a) for i in b])

因为 a 和 b 很大。

有一个函数可以做到这一点,但只适用于一维数组:in1d

最佳答案

我们真正想做的是使用 np.in1d... 除了 np.in1d 仅适用于一维数组。我们的阵列是多维的。但是,我们可以数组视为字符串的一维数组:

arr.view(np.dtype((np.void, arr.dtype.itemsize * arr.shape[-1])))

例如,

In [15]: arr = np.array([[1, 2], [2, 3], [1, 3]])

In [16]: arr = arr.view(np.dtype((np.void, arr.dtype.itemsize * arr.shape[-1])))

In [30]: arr.dtype
Out[30]: dtype('V16')

In [31]: arr.shape
Out[31]: (3, 1)

In [37]: arr
Out[37]:
array([[b'\x01\x00\x00\x00\x00\x00\x00\x00\x02\x00\x00\x00\x00\x00\x00\x00'],
[b'\x02\x00\x00\x00\x00\x00\x00\x00\x03\x00\x00\x00\x00\x00\x00\x00'],
[b'\x01\x00\x00\x00\x00\x00\x00\x00\x03\x00\x00\x00\x00\x00\x00\x00']],
dtype='|V16')

这使得 arr 的每一行都是一个字符串。现在只需要把它连接起来到 np.in1d:

import numpy as np

def asvoid(arr):
"""
Based on http://stackoverflow.com/a/16973510/190597 (Jaime, 2013-06)
View the array as dtype np.void (bytes). The items along the last axis are
viewed as one value. This allows comparisons to be performed on the entire row.
"""
arr = np.ascontiguousarray(arr)
if np.issubdtype(arr.dtype, np.floating):
""" Care needs to be taken here since
np.array([-0.]).view(np.void) != np.array([0.]).view(np.void)
Adding 0. converts -0. to 0.
"""
arr += 0.
return arr.view(np.dtype((np.void, arr.dtype.itemsize * arr.shape[-1])))


def inNd(a, b, assume_unique=False):
a = asvoid(a)
b = asvoid(b)
return np.in1d(a, b, assume_unique)


tests = [
(np.array([[1, 2], [2, 3], [1, 3]]),
np.array([[2, 2], [3, 3], [4, 4]]),
np.array([False, False, False])),
(np.array([[1, 2], [2, 2], [1, 3]]),
np.array([[2, 2], [3, 3], [4, 4]]),
np.array([True, False, False])),
(np.array([[1, 2], [3, 4], [5, 6]]),
np.array([[1, 2], [3, 4], [7, 8]]),
np.array([True, True, False])),
(np.array([[1, 2], [5, 6], [3, 4]]),
np.array([[1, 2], [5, 6], [7, 8]]),
np.array([True, True, False])),
(np.array([[-0.5, 2.5, -2, 100, 2], [5, 6, 7, 8, 9], [3, 4, 5, 6, 7]]),
np.array([[1.0, 2, 3, 4, 5], [5, 6, 7, 8, 9], [-0.5, 2.5, -2, 100, 2]]),
np.array([False, True, True]))
]

for a, b, answer in tests:
result = inNd(b, a)
try:
assert np.all(answer == result)
except AssertionError:
print('''\
a:
{a}
b:
{b}

answer: {answer}
result: {result}'''.format(**locals()))
raise
else:
print('Success!')

产量

Success!

关于python - 测试二维 numpy 数组中的成员资格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16216078/

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