基於NumPy條件,計算陣列與另一個數組按元素進行異或運算後的真值
要計算陣列與另一個數組按元素進行異或運算後的真值,請在 Python NumPy 中使用 **numpy.logical_xor()** 方法。返回值為 True 或 False。這裡我們設定了條件。返回值是應用於 x1 和 x2 元素的邏輯異或運算的布林結果;形狀由廣播確定。如果 x1 和 x2 都是標量,則這是一個標量。
條件會在輸入上進行廣播。在條件為 True 的位置,輸出陣列將設定為 ufunc 結果。在其他位置,輸出陣列將保留其原始值。請注意,如果透過預設的 out=None 建立未初始化的輸出陣列,則其中條件為 False 的位置將保持未初始化狀態。
步驟
首先,匯入所需的庫:
import numpy as np
使用 array() 方法建立兩個 2D NumPy 陣列。我們插入了元素。True 被認為是值 1,False 被認為是值 0:
arr1 = np.array([[True, 8, 7], [13, False, 11]]) arr2 = np.array([[False, 9, True], [19, 25, 6]])
顯示陣列:
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.logical_xor() 方法。返回值為 True 或 False。這裡我們設定了條件:
print("
Result (XOR)...
",np.logical_xor(arr1 > 10, arr2 < 15))示例
import numpy as np
import numpy.ma as ma
# Creating two 2D numpy array using the array() method
# We have inserted elements
# The True is considered value 1
# The False is considered value 0
arr1 = np.array([[True, 8, 7], [13, False, 11]])
arr2 = np.array([[False, 9, True], [19, 25, 6]])
# 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 truth value of an array XOR another array elementwise, use the numpy.logical_xor() method in Python Numpy
# Return value is either True or False
# We have set conditions here
print("
Result (XOR)...
",np.logical_xor(arr1 > 10, arr2 < 15))輸出
Array 1... [[ 1 8 7] [13 0 11]] Array 2... [[ 0 9 1] [19 25 6]] 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 (XOR)... [[ True True True] [ True False False]]
廣告
資料結構
網路
關係資料庫管理系統 (RDBMS)
作業系統
Java
iOS
HTML
CSS
Android
Python
C語言程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP