使用Numpy逐元素計算兩個二維陣列的按位或
要逐元素計算兩個二維陣列的按位或,請在Python Numpy中使用**numpy.bitwise_or()**方法。計算輸入陣列中整數的底層二進位制表示的按位或。此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([[34, 78, 47], [82, 69, 29]]) arr2 = np.array([[59, 98, 36], [81, 55, 32]])
顯示陣列:
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_or()方法:
print("
Result...
",np.bitwise_or(arr1, arr2))示例
import numpy as np
# Creating two 2D numpy arrays using the array() method
# We have inserted elements of int type
arr1 = np.array([[34, 78, 47],
[82, 69, 29]])
arr2 = np.array([[59, 98, 36],
[81, 55, 32]])
# 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 OR of two arrays element-wise, use the numpy.bitwise_or() method in Python Numpy
print("
Result...
",np.bitwise_or(arr1, arr2))輸出
Array 1... [[34 78 47] [82 69 29]] Array 2... [[59 98 36] [81 55 32]] 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... [[ 59 110 47] [ 83 119 61]]
廣告
資料結構
網路
關係資料庫管理系統 (RDBMS)
作業系統
Java
iOS
HTML
CSS
Android
Python
C語言程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP