在Python 3中,我有以下内容NumPy
的数组strings
.
Each string
in the NumPy
数组的形式为b'MD18EE
代替MD18EE
.
例如:
import numpy as np
print(array1)
(b'first_element', b'element',...)
通常情况下,人们会使用.decode('UTF-8')
解码这些元素。
但是,如果我尝试:
array1 = array1.decode('UTF-8')
我收到以下错误:
AttributeError: 'numpy.ndarray' object has no attribute 'decode'
我如何从a中解码这些元素NumPy
大批? (也就是说,我不想b''
)
EDIT:
假设我正在处理一个Pandas
DataFrame
仅某些列以这种方式编码。例如:
import pandas as pd
df = pd.DataFrame(...)
df
COL1 ....
0 b'entry1' ...
1 b'entry2'
2 b'entry3'
3 b'entry4'
4 b'entry5'
5 b'entry6'
你有一个字节串数组;数据类型是S
:
In [338]: arr=np.array((b'first_element', b'element'))
In [339]: arr
Out[339]:
array([b'first_element', b'element'],
dtype='|S13')
astype
轻松将它们转换为 unicode,Py3 的默认字符串类型。
In [340]: arr.astype('U13')
Out[340]:
array(['first_element', 'element'],
dtype='<U13')
还有一个字符串函数库 - 应用相应的str
获取字符串数组元素的方法
In [341]: np.char.decode(arr)
Out[341]:
array(['first_element', 'element'],
dtype='<U13')
The astype
速度更快,但是decode
让您指定编码。
也可以看看如何解码 dtype=numpy.string_ 的 numpy 数组? https://stackoverflow.com/questions/39831230/how-to-decode-a-numpy-array-of-dtype-numpy-string
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)