在 Numpy 中計算陣列與另一個數組的逐元素邏輯與運算結果
要計算陣列與另一個數組的逐元素邏輯與運算結果,可以使用 Python Numpy 中的 **numpy.logical_and()** 方法。返回值為 True 或 False。返回值是應用於 x1 和 x2 元素的邏輯與運算的布林結果;形狀由廣播確定。如果 x1 和 x2 都是標量,則這是一個標量。
out 是儲存結果的位置。如果提供,它必須具有輸入廣播到的形狀。如果沒有提供或為 None,則返回一個新分配的陣列。元組(僅作為關鍵字引數可能)必須具有與輸出數量相等的長度。
步驟
首先,匯入所需的庫 -
import numpy as np
使用 array() 方法建立兩個二維 numpy 陣列。我們插入了元素 -
arr1 = np.array([[True, False, False], [False, True, True]]) arr2 = np.array([[True, False, True], [True, True, 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.logical_and() 方法。返回值為 True 或 False -
print("
Result (AND)...
",np.logical_and(arr1, arr2))示例
import numpy as np
# Creating two 2D numpy array using the array() method
# We have inserted elements
arr1 = np.array([[True, False, False], [False, True, True]])
arr2 = np.array([[True, False, True], [True, True, 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 truth value of an array AND another array elementwise, use the numpy.logical_and() method in Python Numpy
# Return value is either True or False
print("
Result (AND)...
",np.logical_and(arr1, arr2))輸出
Array 1... [[ True False False] [False True True]] Array 2... [[ True False True] [ True True 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 (AND)... [[ True False False] [False True False]]
廣告
資料結構
網路
關係型資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C 語言程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP