解码已在 Numpy 中编码的字符串数组值
numpyserver side programmingprogramming更新于 2025/9/24 18:37:17
要解码已编码的字符串数组值,请使用 Python Numpy 中的 numpy.char.decode() 方法。"encoding"参数设置编码时使用的编码名称。可用的编解码器集合来自 Python 标准库,并可在运行时扩展。结果的类型取决于指定的编码。
numpy.char 模块为 numpy.str_ 或 numpy.bytes_ 类型的数组提供了一组矢量化字符串操作。
步骤
首先,导入所需的库 −
import numpy as np
创建一个一维字符串数组 −
arr = np.array(['Bella', 'Tom', 'John', 'Kate', 'Amy', 'Brad'])
显示我们的数组 −
print("数组...
",arr)
获取数据类型 −
print("
数组数据类型...
",arr.dtype)
获取数组的维度 −
print("
数组维度...
",arr.ndim)
获取数组的形状 −
print("
我们的数组形状...
",arr.shape)
获取数组元素的数量 −
print("
数组中的元素...
",arr.size)
对字符串数组值进行编码。arr 是要进行编码的输入数组 −
e = np.char.encode(arr, encoding='cp037')
print("
Encoded...
",e)
要解码已编码的字符串数组值,请使用 Python Numpy 中的 numpy.char.decode() 方法。"encoding" 参数设置编码 − 时使用的编码名称。
print("
Result (decode)...
",np.char.decode(e, encoding='cp037'))
示例
import numpy as np
# 创建一维字符串数组
arr = np.array(['Bella', 'Tom', 'John', 'Kate', 'Amy', 'Brad'])
# 显示我们的数组
print("数组...
",arr)
# 获取数据类型
print("
数组数据类型...
",arr.dtype)
# 获取数组的维度
print("
数组维度...
",arr.ndim)
# 获取数组的形状
print("
我们的数组形状...
",arr.shape)
# 获取数组元素的数量
print("
数组中的元素...
",arr.size)
# 编码字符串数组值
# arr 是要编码的输入数组
e = np.char.encode(arr, encoding='cp037')
print("
Encoded...
",e)
# 要解码已编码的字符串数组值,请使用 Python Numpy 中的 numpy.char.decode() 方法
# "encoding" 参数设置编码时使用的编码名称
print("
Result (decode)...
",np.char.decode(e, encoding='cp037'))
输出
数组... ['Bella' 'Tom' 'John' 'Kate' 'Amy' 'Brad'] 数组数据类型... <U5 数组维度... 1 我们的数组形状... (6,) 数组中的元素... 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']

