【问题标题】:Conversion from U3 dtype to ascii从 U3 dtype 转换为 ascii
【发布时间】:2016-12-02 22:37:54
【问题描述】:

我正在从 .mat 文件中读取数据。数据在 numpy 数组中。

[array([u'ABT'], dtype='<U3')] 

这是数组的一个元素。我只想从数组中获取值“ABT”。 Unicode 规范化和编码为 ascii 函数不起作用。

【问题讨论】:

    标签: python numpy unicode ascii


    【解决方案1】:

    encode 是一个字符串方法,所以不能直接作用于字符串数组。但是有几种方法可以将它应用于每个字符串

    这里我用的是 Py3,所以默认是 unicode。

    In [179]: A=np.array(['one','two'])
    In [180]: A
    Out[180]: 
    array(['one', 'two'], 
          dtype='<U3')
    

    普通迭代:

    In [181]: np.array([s.encode() for s in A])
    Out[181]: 
    array([b'one', b'two'], 
          dtype='|S3')
    

    np.char 具有将字符串方法应用于数组的每个元素的函数:

    In [182]: np.char.encode(A)
    Out[182]: 
    array([b'one', b'two'], 
          dtype='|S3')
    

    但看起来这是astype 可以处理的转换之一:

    In [183]: A.astype('<S3')
    Out[183]: 
    array([b'one', b'two'], 
          dtype='|S3')
    

    并受到最近关于np.chararray 的问题的启发: What happened to numpy.chararray

    In [191]: Ac=np.char.array(A)
    In [192]: Ac
    Out[192]: 
    chararray(['one', 'two'], 
          dtype='<U3')
    In [193]: Ac.encode()
    Out[193]: 
    array([b'one', b'two'], 
          dtype='|S3')
    

    【讨论】:

      猜你喜欢
      • 2011-05-20
      • 2017-09-15
      • 1970-01-01
      • 2014-10-21
      • 2017-01-20
      • 2018-10-16
      • 1970-01-01
      • 2015-06-04
      • 1970-01-01
      相关资源
      最近更新 更多