如何解码dtype = numpy.string_的numpy数组? [英] How to decode a numpy array of dtype=numpy.string_?

查看:154
本文介绍了如何解码dtype = numpy.string_的numpy数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要使用Python 3解码以以下方式编码的字符串:

I need to decode, with Python 3, a string that was encoded the following way:

>>> s = numpy.asarray(numpy.string_("hello\nworld"))
>>> s
array(b'hello\nworld', 
      dtype='|S11')

我尝试过:

>>> str(s)
"b'hello\\nworld'"

>>> s.decode()
AttributeError                            Traceback (most recent call last)
<ipython-input-31-7f8dd6e0676b> in <module>()
----> 1 s.decode()

AttributeError: 'numpy.ndarray' object has no attribute 'decode'

>>> s[0].decode()
---------------------------------------------------------------------------
IndexError                                Traceback (most recent call last)
<ipython-input-34-fae1dad6938f> in <module>()
----> 1 s[0].decode()

IndexError: 0-d arrays can't be indexed

推荐答案

另一个选择是字符串操作的np.char集合.

Another option is the np.char collection of string operations.

In [255]: np.char.decode(s)
Out[255]: 
array('hello\nworld', 
      dtype='<U11')

如果需要,它接受encoding关键字.但是如果您不需要.astype,可能会更好.

It accepts the encoding keyword if needed. But .astype is probably better if you don't need this.

s为0d(形状()),因此需要用s[()]进行索引.

This s is 0d (shape ()), so needs to be indexed with s[()].

In [268]: s[()]
Out[268]: b'hello\nworld'
In [269]: s[()].decode()
Out[269]: 'hello\nworld'

s.item()也可以.

这篇关于如何解码dtype = numpy.string_的numpy数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆