使用 NumPy 元素级计算两个二维数组的按位与
要计算两个二维数组的按位与,可以使用 Python NumPy 中的 numpy.bitwise_and() 方法。计算输入数组中整数的底层二进制表示的按位与。此 ufunc 实现 C/Python 运算符 &。
第一个和第二个参数是数组,仅处理整数和布尔类型。如果 x1.shape != x2.shape,则它们必须能够广播到一个共同的形状。
where 参数是在输入上广播的条件。在条件为 True 的位置,out 数组将设置为 ufunc 结果。在其他地方,out 数组将保留其原始值。请注意,如果通过默认的 out=None 创建未初始化的 out 数组,则其中条件为 False 的位置将保持未初始化状态。
步骤
首先,导入所需的库 -
import numpy as np
使用 array() 方法创建两个二维 NumPy 数组。我们已插入 int 类型的元素 -
arr1 = np.array([[49, 6, 61], [82, 69, 29]]) arr2 = np.array([[40, 60, 61], [81, 55, 32]])
显示数组 -
print("Array 1...
", arr1)
print("
Array 2...
", arr2)获取数组的类型 -
print("
Our Array 1 type...
", arr1.dtype)
print("
Our Array 2 type...
", arr2.dtype)获取数组的维度 -
print("
Our Array 1 Dimensions...
",arr1.ndim)
print("
Our Array 2 Dimensions...
",arr2.ndim)获取数组的形状 -
print("
Our Array 1 Shape...
",arr1.shape)
print("
Our Array 2 Shape...
",arr2.shape)要计算两个二维数组的按位与,请使用 numpy.bitwise_and() 方法 -
print("
Result...
",np.bitwise_and(arr1, arr2))示例
import numpy as np
# Creating two 2D numpy arrays using the array() method
# We have inserted elements of int type
arr1 = np.array([[49, 6, 61],
[82, 69, 29]])
arr2 = np.array([[40, 60, 61],
[81, 55, 32]])
# Display the arrays
print("Array 1...
", arr1)
print("
Array 2...
", arr2)
# Get the type of the arrays
print("
Our Array 1 type...
", arr1.dtype)
print("
Our Array 2 type...
", arr2.dtype)
# Get the dimensions of the Arrays
print("
Our Array 1 Dimensions...
",arr1.ndim)
print("
Our Array 2 Dimensions...
",arr2.ndim)
# Get the shape of the Arrays
print("
Our Array 1 Shape...
",arr1.shape)
print("
Our Array 2 Shape...
",arr2.shape)
# To compute the bit-wise AND of two arrays element-wise, use the numpy.bitwise_and() method in Python Numpy
print("
Result...
",np.bitwise_and(arr1, arr2))输出
Array 1... [[49 6 61] [82 69 29]] Array 2... [[40 60 61] [81 55 32]] Our Array 1 type... int64 Our Array 2 type... int64 Our Array 1 Dimensions... 2 Our Array 2 Dimensions... 2 Our Array 1 Shape... (2, 3) Our Array 2 Shape... (2, 3) Result... [[32 4 61] [80 5 0]]
广告
数据结构
网络
关系数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP