要解碼已經使用 Numpy 編碼的字串陣列值


要解碼已經編碼的字串陣列值,在 Python Numpy 中使用 numpy.char.decode() 方法。在 codificate 編碼時,“編碼”引數設定呼叫的編碼的名稱。可用編碼器集合取自 Python 標準庫,且可以在執行時對其進行擴充套件。結果的型別取決於指定的編碼。

numpy.char 模組提供了一組用於型別為 numpy.str_ 或 numpy.bytes_ 的陣列的向量化字串運算。

步驟

首先,匯入所需的庫

import numpy as np

建立一個字串的一維陣列

arr = np.array(['Bella', 'Tom', 'John', 'Kate', 'Amy', 'Brad'])

顯示我們的陣列

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)

對字串陣列值進行編碼。arr 是要進行編碼的輸入陣列

e = np.char.encode(arr, encoding='cp037')
print("
Encoded...
",e)

要解碼已經編碼的字串陣列值,在 Python Numpy 中使用 numpy.char.decode() 方法。“編碼”引數設定 codificate 編碼時呼叫的編碼的名稱

print("
Result (decode)...
",np.char.decode(e, encoding='cp037'))

示例

import numpy as np

# Create a One-Dimensional array of string
arr = np.array(['Bella', 'Tom', 'John', 'Kate', 'Amy', 'Brad'])

# 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) # Encode string array values # The arr is the input array to be encoded e = np.char.encode(arr, encoding='cp037') print("
Encoded...
",e) # To decode string array values that is already encoded, use the numpy.char.decode() method in Python Numpy # The "encoding" parameter sets the name of the encode used while encoding print("
Result (decode)...
",np.char.decode(e, encoding='cp037'))

輸出

Array...
['Bella' 'Tom' 'John' 'Kate' 'Amy' 'Brad']

Array datatype...
<U5

Array Dimensions...
1

Our Array Shape...
(6,)

Elements in the Array...
6

Encoded...
[b'\xc2\x85\x93\x93\x81' b'\xe3\x96\x94' b'\xd1\x96\x88\x95'
b'\xd2\x81\xa3\x85' b'\xc1\x94\xa8' b'\xc2\x99\x81\x84']

Result (decode)...
['Bella' 'Tom' 'John' 'Kate' 'Amy' 'Brad']

更新時間: 2022 年 2 月 17 日

830 次觀看

開啟你的 職業生涯

完成課程以獲得認證

開始
廣告
© . All rights reserved.