2016-02-01 54 views
1

我想创建一个numpy数组与字符串组件。我已经使用了下面的命令,它的输出显示。Numpy数组与字符串组件

>>> a = np.full((2,2), 'hello', dtype='S5') 
>>> a 
array([[b'hello', b'hello'], 
     [b'hello', b'hello']], 
     dtype='|S5') 

你能解释为什么数组组件显示为b'hello而不是'hello'?我期待阵列显示为:

>>> a 
array([['hello', 'hello'], 
     ['hello', 'hello']], 
    dtype='|S5') 

回答

0

我认为这是由于你的dtype你可以转换为常用字符串bytes.decode。从docs

'S''a'(字节级)字符串

所以有字节串和字节串都表现出与b前缀,你也可以检查你的elemets类型:

In [206]: type(a[0][0]) 
Out[206]: numpy.bytes_ 

对于从bytes转换为string

In [189]: [list(map(bytes.decode, i)) for i in a] 
Out[189]: [['hello', 'hello'], ['hello', 'hello']] 

或者你可以创建一个字符串unicodeU D型的数组:

a = np.full((2,2), 'hello', dtype='U5') 

In [191]: a 
Out[191]: 
array([['hello', 'hello'], 
     ['hello', 'hello']], dtype='<U5') 
+0

这是一个python3的问题,其中的字符串是正常的Unicode。 – hpaulj

+0

@hpaulj我不确定这是个问题。据我了解,这只是另一种行为。 –

+0

'b'不出现在python2显示中。如果dtype是'U5',则'u'。 – hpaulj