在 NumPy 中計算帶符號整數型別陣列的按位非運算


要計算帶符號整數型別陣列的按位非運算,請在 Python NumPy 中使用 **numpy.bitwise_not()** 方法。計算輸入陣列中整數的底層二進位制表示的按位非運算。此 ufunc 實現 C/Python 運算子 ~。

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

NumPy 提供全面的數學函式、隨機數生成器、線性代數例程、傅立葉變換等等。它支援各種硬體和計算平臺,並且與分散式、GPU 和稀疏陣列庫配合良好。

步驟

首先,匯入所需的庫:

import numpy as np

建立一個二維陣列。資料型別使用“dtype”引數設定。我們將資料型別設定為帶符號整數型別。使用帶符號整數型別時,結果是無符號型別結果的二進位制補碼:

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

顯示我們的陣列:

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
# The datatype is set using the "dtype" parameter
# We have set the datatype to signed integer type
# When using signed integer types the result is the two's complement of the result for the unsigned type
arr = np.array([[92, 81, 98, 45], [22, 67, 54, 69 ], [69, 80, 80, 99]], dtype=np.int8)

# 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-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]
[69 80 80 99]]

Array datatype...
int8

Array Dimensions...
2

Our Array Shape...
(3, 4)

Elements in the Array...
12

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

更新於:2022年2月17日

116 次瀏覽

啟動您的 職業生涯

完成課程獲得認證

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