gpt4 book ai didi

python - NumPy - 如何按位遍历矩阵行中的每个元素

转载 作者:太空宇宙 更新时间:2023-11-03 13:34:36 24 4
gpt4 key购买 nike

我想寻求更好的方法来按位遍历矩阵行中的所有元素。

我有一个数组:

import numpy as np
A = np.array([[1,1,1,4], #shape is (3, 5) - one sample
[4,8,8,16],
[4,4,4,4]],
dtype=np.uint16)

B = np.array([[[1,1,1,4], #shape is (2, 3, 5) - two samples
[4,8,8,16],
[4,4,4,4]],
[[1,1,1,4],
[4,8,8,16],
[4,4,4,4]]]
dtype=np.uint16)

示例和预期输出:

resultA = np.bitwise_and(A, axis=through_rows) # doesn't work 
# expected output should be a bitwise and over elements in rows resultA:
array([[0],
[0],
[4]])

resultB = np.bitwise_and(B, axis=through_rows) # doesn't work
# expected output should be a bitwise and over elements in rows
# for every sample resultB:

array([[[0],
[0],
[4]],

[[0],
[0],
[4]]])

但我的输出是:

resultA = np.bitwise_and(A, axis=through_rows) # doesn't work
File "<ipython-input-266-4186ceafed83>", line 13
dtype=np.uint16)
^
SyntaxError: invalid syntax

因为 numpy.bitwise_and(x1, x2[, out]) 有两个数组作为输入。如何获得预期的输出?

最佳答案

这个的专用函数是bitwise_and.reduce:

resultB = np.bitwise_and.reduce(B, axis=2)

不幸的是in numpy prior to v1.12.0 bitwise_and.identity 是 1,所以这行不通。对于那些旧版本,解决方法如下:

resultB = np.bitwise_and.reduceat(B, [0], axis=2)

关于python - NumPy - 如何按位遍历矩阵行中的每个元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41761479/

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