2016-07-28 93 views
2

我正在从.mat文件读取数据。数据在numpy数组中。从U3 dtype转换为ascii

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

这是数组的一个元素。我只想从数组中获得值'ABT'。 Unicode正常化和编码为ASCII功能不起作用。

回答

0

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.chararrayWhat 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')