在 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]]
廣告