計算兩個一維 NumPy 陣列的按元素位與運算


要計算兩個一維陣列的按元素位與運算,請在 Python NumPy 中使用 **numpy.bitwise_and()** 方法。此方法計算輸入陣列中整數的底層二進位制表示的按位與運算。此 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([32, 95, 82, 69, 38])
arr2 = np.array([28, 60, 81, 55, 89])

顯示陣列:

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_and() 方法:

print("
Result...
",np.bitwise_and(arr1, arr2))

示例

import numpy as np

# Creating two 1D numpy arrays using the array() method
# We have inserted elements of int type
arr1 = np.array([32, 95, 82, 69, 38])
arr2 = np.array([28, 60, 81, 55, 89])

# 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 AND of two arrays element-wise, use the numpy.bitwise_and() method in Python Numpy print("
Result...
",np.bitwise_and(arr1, arr2))

輸出

Array 1...
[32 95 82 69 38]

Array 2...
[28 60 81 55 89]

Our Array 1 type...
int64

Our Array 2 type...
int64

Our Array 1 Dimensions...
1

Our Array 2 Dimensions...
1

Our Array 1 Shape...
(5,)

Our Array 2 Shape...
(5,)

Result...
[ 0 28 80 5 0]

更新於:2022年2月18日

119 次瀏覽

啟動你的職業生涯

透過完成課程獲得認證

開始學習
廣告
© . All rights reserved.