在 Numpy 中對二維陣列進行逐元素按位取反運算


要對二維陣列進行逐元素按位取反運算,可以使用 Python Numpy 中的 **numpy.bitwise_not()** 方法。

計算輸入陣列中整數的底層二進位制表示的按位取反。此 ufunc 實現 C/Python 運算子 ~。

where 引數是在輸入上廣播的條件。在條件為 True 的位置,out 陣列將設定為 ufunc 結果。在其他位置,out 陣列將保留其原始值。請注意,如果透過預設的 out=None 建立未初始化的 out 陣列,則其中條件為 False 的位置將保持未初始化狀態。

步驟

首先,匯入所需的庫 -

import numpy as np

建立一個二維陣列 -

arr = np.array([[92, 81, 98, 45], [22, 67, 54, 69 ]])

顯示我們的陣列 -

print("Array...
",arr)

獲取資料型別 -

print("
Array datatype...
",arr.dtype)

獲取陣列的維度 -

print("
Array Dimensions...
",arr.ndim)

獲取陣列的形狀 -

print("
Our Array Shape...
",arr.shape)

獲取陣列的元素數量 -

print("
Elements in the Array...
",arr.size)

要對二維陣列進行逐元素按位取反運算,可以使用 Python Numpy 中的 numpy.bitwise_not() 方法 -

print("
Result (bit-wise NOT)...
",np.bitwise_not(arr))

示例

import numpy as np

# Create a 2d array
arr = np.array([[92, 81, 98, 45], [22, 67, 54, 69 ]])

# Displaying our array
print("Array...
",arr) # Get the datatype print("
Array datatype...
",arr.dtype) # Get the dimensions of the Array print("
Array Dimensions...
",arr.ndim) # Get the shape of the Array print("
Our Array Shape...
",arr.shape) # Get the number of elements of the Array print("
Elements in the Array...
",arr.size) # To compute the bit-wise NOT of an array element-wise, use the numpy.bitwise_not() method in Python Numpy print("
Result (bit-wise NOT)...
",np.bitwise_not(arr))

輸出

Array...
[[92 81 98 45]
[22 67 54 69]]

Array datatype...
int64

Array Dimensions...
2

Our Array Shape...
(2, 4)

Elements in the Array...
8

Result (bit-wise NOT)...
[[-93 -82 -99 -46]
[-23 -68 -55 -70]]

更新於: 2022-02-17

124 次瀏覽

開啟你的 職業生涯

透過完成課程獲得認證

開始學習
廣告

© . All rights reserved.