NumPy - 二元运算符
NumPy - 按位二进制运算符
Section titled “NumPy - 按位二进制运算符”NumPy 提供了用于对整型数组执行逐元素按位操作的函数。这些函数对应于许多编程语言中标准的按位操作。
可用函数包括:
| 函数 | 描述 | 等效运算符 |
|---|---|---|
numpy.bitwise_and() | 计算数组元素的按位与。 | & |
numpy.bitwise_or() | 计算数组元素的按位或。 | | |
numpy.bitwise_xor() | 计算数组元素的按位异或。 | ^ |
numpy.invert() 或 numpy.bitwise_not() | 计算数组元素的按位非(取反)。 | ~ |
numpy.left_shift() | 将数组元素的位向左移动。 | << |
numpy.right_shift() | 将数组元素的位向右移动。 | >> |
这些操作对整型 NumPy 数组进行逐元素计算。你可以使用函数(例如 np.bitwise_and(a, b))或运算符(例如 a & b)。
示例:bitwise_and (&)
Section titled “示例:bitwise_and (&)”import numpy as np
a = np.array([10, 20, 30], dtype=np.uint8) # 二进制:00001010, 00010100, 00011110b = np.array([ 5, 15, 25], dtype=np.uint8) # 二进制:00000101, 00001111, 00011001
result_func = np.bitwise_and(a, b)result_op = a & b
print(f"Array a: {a}")print(f"Array b: {b}")print(f"np.bitwise_and(a, b): {result_func}") # 0, 4, 24print(f"a & b: {result_op}")示例:bitwise_or (|)
Section titled “示例:bitwise_or (|)”import numpy as np
a = np.array([10, 20], dtype=np.uint8) # 00001010, 00010100b = np.array([ 5, 15], dtype=np.uint8) # 00000101, 00001111
result_func = np.bitwise_or(a, b)result_op = a | b
print(f"Array a: {a}")print(f"Array b: {b}")print(f"np.bitwise_or(a, b): {result_func}") # 15, 31print(f"a | b: {result_op}")示例:invert (~)
Section titled “示例:invert (~)”注意:按位取反取决于整型类型(例如 uint8、int16)。对于像 uint8 这样的无符号整型,它会翻转所有 8 位。
import numpy as np
a = np.array([10, 20], dtype=np.uint8) # 二进制:00001010, 00010100
result_func = np.invert(a)result_op = ~a
print(f"Array a: {a}")print(f"np.invert(a): {result_func}") # 245 (11110101), 235 (11101011)print(f"~a: {result_op}")示例:left_shift (<<)
Section titled “示例:left_shift (<<)”import numpy as np
a = np.array([2, 8], dtype=np.uint8) # 二进制:00000010, 00001000shift_amount = 2
result_func = np.left_shift(a, shift_amount)result_op = a << shift_amount
print(f"Array a: {a}")print(f"Shift amount: {shift_amount}")print(f"np.left_shift(a, {shift_amount}): {result_func}") # 8 (00001000), 32 (00100000)print(f"a << {shift_amount}: {result_op}")示例:right_shift (>>)
Section titled “示例:right_shift (>>)”import numpy as np
a = np.array([8, 32], dtype=np.uint8) # 二进制:00001000, 00100000shift_amount = 2
result_func = np.right_shift(a, shift_amount)result_op = a >> shift_amount
print(f"Array a: {a}")print(f"Shift amount: {shift_amount}")print(f"np.right_shift(a, {shift_amount}): {result_func}") # 2 (00000010), 8 (00001000)print(f"a >> {shift_amount}: {result_op}")这些按位操作常用于涉及底层数据操作、设置/清除标志位中的特定位、图像处理掩码或高效实现某些算法的任务中。