在 NumPy 中逐元素计算两个布尔数组的按位异或
要逐元素计算两个布尔数组的按位异或,请在 Python NumPy 中使用 **numpy.bitwise_xor()** 方法。
计算输入数组中整数的底层二进制表示的按位异或。此 ufunc 实现 C/Python 运算符 ^。
第一个和第二个参数是数组,只处理整数和布尔类型。如果 x1.shape != x2.shape,则它们必须可广播到公共形状。
步骤
首先,导入所需的库:
import numpy as np
使用 array() 方法创建两个 NumPy 布尔数组:
arr1 = np.array([[False, False, False], [True, False, True]]) arr2 = np.array([[False, True, False], [False, False, False]])
显示数组:
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_xor():
print("
Result (Bit-wise XOR)...
",np.bitwise_xor(arr1, arr2))示例
import numpy as np
# Creating two numpy boolean arrays using the array() method
arr1 = np.array([[False, False, False],
[True, False, True]])
arr2 = np.array([[False, True, False],
[False, False, False]])
# 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 XOR of two arrays element-wise, use the numpy.bitwise_xor() method in Python Numpy
print("
Result (Bit-wise XOR)...
",np.bitwise_xor(arr1, arr2))输出
Array 1... [[False False False] [ True False True]] Array 2... [[False True False] [False False False]] Our Array 1 type... bool Our Array 2 type... bool Our Array 1 Dimensions... 2 Our Array 2 Dimensions... 2 Our Array 1 Shape... (2, 3) Our Array 2 Shape... (2, 3) Result (Bit-wise XOR)... [[False True False] [ True False True]]
广告
数据结构
网络
关系数据库管理系统 (RDBMS)
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP