要解码已经使用 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']
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP