如何解码 dtype=numpy.string_ 的 numpy 数组?

2024-05-10

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

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

I tried:

>>> 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字符串操作的集合。

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

它接受encoding如果需要的话可以使用关键字。但.astype如果你不需要这个可能会更好。

This s是 0d (shape ()),所以需要用s[()].

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

s.item()也有效。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何解码 dtype=numpy.string_ 的 numpy 数组? 的相关文章

随机推荐