對 NumPy 中的字串陣列值進行編碼


若要編碼字串陣列值,請在 Python NumPy 中使用 numpy.char.encode() 方法。arr 是要編碼的輸入陣列。“encoding”引數設定編碼的名稱。現成的編解碼器集合來自 Python 標準庫,且可以在執行時進行擴充套件。結果的型別取決於指定的編碼。

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

步驟

首先,匯入所需的庫 −

import numpy as np

建立一個一維字串陣列 −

arr = np.array(['zbellazz' 'zztoMzzz' 'zzjohnzz' 'zzkatEzz' 'zzamyzzz' 'zzbradzz'])

顯示我們的陣列 −

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.char.encode() 方法。arr 是要編碼的輸入陣列。“encoding”引數設定編碼的名稱 −

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

示例

import numpy as np

# Create a One-Dimensional array of string
arr = np.array(['zbellazz' 'zztoMzzz' 'zzjohnzz' 'zzkatEzz' 'zzamyzzz' 'zzbradzz'])

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

輸出

Array...
['zbellazzzztoMzzzzzjohnzzzzkatEzzzzamyzzzzzbradzz']

Array datatype...
<U48

Array Dimensions...
1

Our Array Shape...
(1,)

Elements in the Array...
1

Result (encode)...
[b'\xa9\x82\x85\x93\x93\x81\xa9\xa9\xa9\xa9\xa3\x96\xd4\xa9\xa9\xa9\xa9\xa9\x91\x96\x88\x95\xa9\xa9\xa9\xa9\x92\x81\xa3\xc5\xa9\xa9\xa9\xa9\x81\x94\xa8\xa9\xa9\xa9\xa9\xa9\x82\x99\x81\x84\xa9\xa9']

更新於: 2022-02-17

1K+ 瀏覽量

開啟您的 職業生涯

完成課程獲得認證

立即開始
廣告
© . All rights reserved.