在 Python 3 中,我有以下内容 NumPy
strings
的数组.
每个string
在 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'
我如何从
NumPy
解码这些元素大批? (也就是说,我不想要 b''
)编辑:
假设我正在处理一个
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')
astype
速度更快,但 decode
允许您指定编码。另见 How to decode a numpy array of dtype=numpy.string_?
关于arrays - 如何在 Python3 中解码编码文字/字符串的 numpy 数组?属性错误 : 'numpy.ndarray' object has no attribute 'decode' ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40388792/