NumPy 的 bitwise_and() 函式



NumPy 的bitwise_and()函式對兩個陣列中對應元素執行按位與運算。此函式透過比較輸入元素的二進位制表示來進行操作,如果輸入陣列中對應的位都為 1,則結果中的每個位都設定為 1,否則,該位設定為 0。

此運算是按元素進行的,這意味著獨立處理輸入陣列中的每對元素。bitwise_and()支援廣播,允許它透過根據廣播規則對齊陣列來處理不同形狀的陣列。

此函式可用於二進位制資料操作和低階資料處理。以下是按位與運算對 1 和 0 的位組合的結果:

  • 0 和 0 的按位與:0
  • 0 和 1 的按位與:0
  • 1 和 0 的按位與:0
  • 1 和 1 的按位與:1

語法

以下是 NumPy bitwise_and()函式的語法:

numpy.bitwise_or(x1, x2, /, out=None, *, where=True, casting='same_kind', order='K', dtype=None, subok=True[, signature])

引數

以下是 NumPy bitwise_and()函式的引數:

  • x1: 第一個輸入陣列或標量。
  • x2: 第二個輸入陣列或標量。必須可廣播到x1的形狀。
  • out(可選):結果儲存到的位置。如果提供,則其形狀必須與x1x2的廣播輸出匹配。
  • where(可選):確定執行運算位置的條件。在此條件為 True 的位置計算結果。
  • **kwargs: 其他關鍵字引數。

返回值

此函式返回包含按位與運算結果的陣列。

示例 1

以下是 NumPy bitwise_and()函式的基本示例。此示例演示如何計算兩個數字的按位與。

import numpy as np 

# Print binary equivalents of 13 and 17
print('Binary equivalents of 13 and 17:')
a, b = 13, 17
print(bin(a), bin(b))
print('\n')  

# Print bitwise AND of 13 and 17
print('Bitwise AND of 13 and 17:')
print(np.bitwise_and(a, b))

以下是將bitwise_and()函式應用於數字 13 和 17 的輸出:

Binary equivalents of 13 and 17:
0b1101 0b10001

Bitwise AND of 13 and 17:
1

示例 2

在此示例中,我們演示如何建立兩個 2D NumPy 陣列,顯示它們的屬性並計算它們的按元素按位與。

import numpy as np

# Creating two numpy arrays using the array() method
# We have inserted elements of int type
arr1 = np.array([[49, 6, 61],
                 [82, 69, 29]])
arr2 = np.array([[40, 60, 61],
                 [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 AND of two arrays element-wise, use the numpy.bitwise_and() method in Python Numpy
print("Result:",np.bitwise_and(arr1, arr2))

以下是上述示例的輸出:

Array 1: [[49  6 61]
 [82 69 29]]
Array 2: [[40 60 61]
 [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: [[32  4 61]
 [80  5  0]]
numpy_binary_operators.htm
廣告