【问题标题】:How to decode a numpy array of dtype=numpy.string_?如何解码 dtype=numpy.string_ 的 numpy 数组?
【发布时间】:2017-02-11 09:01:21
【问题描述】:

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

>>> 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

【问题讨论】:

    标签: python string python-3.x numpy


    【解决方案1】:

    另一个选项是np.char 字符串操作集合。

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

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

    这个s是0d(shape()),所以需要用s[()]索引。

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

    s.item() 也可以。

    【讨论】:

      【解决方案2】:

      在 Python 3 中,有两种类型表示字符序列:bytesstr(包含 Unicode 字符)。当您使用string_ 作为您的类型时,numpy 将返回bytes。如果你想要常规的str,你应该使用unicode_ 输入numpy:

      >>> s = numpy.asarray(numpy.unicode_("hello\nworld"))
      >>> s
      array('hello\nworld', 
            dtype='<U11')
      
      >>> str(s)
      'hello\nworld'
      

      但请注意,如果您没有为字符串指定类型(string_ 或 unicode_),它将返回默认的 str 类型(在 python 3.x 中是 str(包含 unicode 字符))。

      >>> s = numpy.asarray("hello\nworld")
      >>> str(s)
      'hello\nworld'
      

      【讨论】:

      • 我使用 numpy.string_ 数据编码的原因是为了兼容性。我的数据采用一种称为 HDF5 的数据格式,并且可以被 Python 以外的其他软件读取。
      • @PiRK 如果你想在 python 版本之间使用兼容的方法,你应该使用 numpy.asarray() 否则它与 python 无关。
      • 不幸的是,我还需要我的输出 HDF5 文件与旧的 Fortran 库、各种版本的 Octave 软件、Matlab...等兼容
      【解决方案3】:

      如果我的理解是正确的,你可以用astype 来做这件事,如果copy = False 将返回包含相应类型内容的数组:

      >>> s = numpy.asarray(numpy.string_("hello\nworld"))
      >>> r = s.astype(str, copy=False)
      >>> r 
      array('hello\nworld', 
            dtype='<U11')
      

      【讨论】:

      • 谢谢!这很有帮助。现在我可以通过这种方式恢复我的字符串:s = str(s.astype(str))
      • 直接用unicode_获取正则str就不需要转换类型了。
      • 我不控制编码阶段。在我的实际问题中,我不会自己创建s。我只是碰巧知道它在这个编码阶段之后被写入了一个文件。
      猜你喜欢
      • 2015-11-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-11-19
      • 2011-12-07
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多