在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([32, 95, 82, 69, 38, 49]) arr2 = np.array(99)
显示数组:
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 numpy arrays using the array() method
# We have inserted elements of int type
arr1 = np.array([32, 95, 82, 69, 38, 49])
arr2 = np.array(99)
# 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... [32 95 82 69 38 49] Array 2... 99 Our Array 1 type... int64 Our Array 2 type... int64 Our Array 1 Dimensions... 1 Our Array 2 Dimensions... 0 Our Array 1 Shape... (6,) Our Array 2 Shape... () Result... [32 67 66 65 34 33]
广告
数据结构
网络
关系数据库管理系统 (RDBMS)
操作系统
Java
iOS
HTML
CSS
Android
Python
C语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP