gpt4 book ai didi

python - 检查列表中的值是否位于 numpy 数组的相应行中

转载 作者:行者123 更新时间:2023-12-01 09:17:47 24 4
gpt4 key购买 nike

b =np.ndarray(shape=(5,5), dtype=int, order='F')
Out[142]:
array([[ 1, 65536, 0, 0, 0],
[ 0, 0, 1, 65536, 0],
[16777216, 0, 0, 0, 1],
[ 0, 256, 16777216, 0, 0],
[ 0, 0, 0, 256, 16777216]])

我有一个列表,例如:

a = [1,23,4,5,20,0...]

我想检查每个索引 a 中的值是否位于 b 中的相应行中,如 np.isin(a[0] , b[0]) 并接收所有行的 bool 向量(如果 a[i] 位于 b[i] 中)。

a 的长度等于 b 的长度(行数)。

最佳答案

这是使用 np.ndarray.any 的一种方法。只需注意对齐尺寸以允许广播即可。

np.random.seed(0)

b = np.random.randint(0, 10, (5, 5))
a = np.random.randint(0, 10, 5)

print(a, b, sep='\n'*2)

[3 0 3 5 0]

[[5 0 3 3 7]
[9 3 5 2 4]
[7 6 8 8 1]
[6 7 7 8 1]
[5 9 8 9 4]]

c = (a[:, None] == b).any(1)

print(c)

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

关于python - 检查列表中的值是否位于 numpy 数组的相应行中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51084043/

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