对 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.