如何在numpy中创建字符数组?

Uri*_*son 15 python string numpy character-encoding

说我有以下数组:

import numpy as np
a = ['hello','snake','plate']
Run Code Online (Sandbox Code Playgroud)

我希望它变成一个numpy数组,b以便:

b[0,0] = 'h'
b[0,1] = 'e'
b[0,2] = 'l'
b[1,0] = 's'
...
Run Code Online (Sandbox Code Playgroud)

我想要标准的numpy技巧,如广播,比较等.

怎么做?numpy文档中的这个位置在哪里?

谢谢!

乌里

Joe*_*ton 17

实际上,你可以在numpy中没有任何副本或列表推导的情况下这样做(关于非等长字符串的警告......).只需将其视为1个字符的字符串数组并重新整形:

import numpy as np

x = np.array(['hello','snake','plate'], dtype=str)
y = x.view('S1').reshape((x.size, -1))

print repr(y)
Run Code Online (Sandbox Code Playgroud)

这会产生:

array([['h', 'e', 'l', 'l', 'o'],
       ['s', 'n', 'a', 'k', 'e'],
       ['p', 'l', 'a', 't', 'e']], 
      dtype='|S1')
Run Code Online (Sandbox Code Playgroud)

但一般来说,在大多数情况下,我会避免使用numpy数组来存储字符串.有些情况下它很有用,但你最好坚持使用允许可变长度字符串的数据结构,以及保持字符串.

  • 对于 python3,如果字符串是 ascii 字符串,则需要编写 dtype=bytes (2认同)

mat*_*fee 11

您可以直接创建一个numpy字符数组,例如:

b = np.array([ ['h','e','l','l','o'],['s','n','a','k','e'],['p','l','a','t','e'] ])
Run Code Online (Sandbox Code Playgroud)

通常的数组技巧适用于此.

如果您有a并希望从中生成 b,请注意:

list('hello') == ['h','e','l','l','o']
Run Code Online (Sandbox Code Playgroud)

所以你可以这样做:

b = np.array([ list(word) for word in a ])
Run Code Online (Sandbox Code Playgroud)

但是,如果a有不等长的单词(例如['snakes','on','a','plane']),你想用较短的单词做什么?你可以用空格填充最长的单词:

wid = max(len(w) for w in a)
b = np.array([ list(w.center(wid)) for w in a])
Run Code Online (Sandbox Code Playgroud)

哪个string.center(width)垫有空格,以弦为中心.您也可以使用rjustljust(参见字符串文档).