如何在numpy中创建字符数组? [英] How do I create character arrays in numpy?

查看:1444
本文介绍了如何在numpy中创建字符数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

说我有以下数组:

  import numpy as np 
a = ['hello','snake ','plate']



我想把它变成一个numpy数组 b 以便:

  b [0,0] ='h'
b [ 0,1] ='e'
b [0,2] ='l'
b [1,0] ='s'
...



我想让标准的numpy技巧工作,比如广播,比较等。



如何做?



$ r
$ b

解决方案

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

  b'='n','a','k','e' ],['p','l','a','t','e']] 


$ b



如果你有 a ,并希望请注意:

  list('hello')== ['h' e','l','l','o'] 

  b = np.array(a中的单词列表(word))

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

  wid = max(len(w)for w in a)
b = np.array([list(w.center(wid))for w in a])

其中 string.center(width)用空格填充,以字符串为中心。您也可以使用 rjust ljust (请参阅 string docs )。


Say I have the following array:

import numpy as np
a = ['hello','snake','plate']

I want this to turn into a numpy array b so that:

b[0,0] = 'h'
b[0,1] = 'e'
b[0,2] = 'l'
b[1,0] = 's'
...

I want the standard numpy tricks to work, like broadcasting, comparison, etc.

How is it done? And where is this in the numpy documentation?

Thanks!

Uri

解决方案

You can create a numpy character array directly e.g.:

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

The usual array tricks work with this.

If you have a and wish to generate b from it, note that:

list('hello') == ['h','e','l','l','o']

So you can do something like:

b = np.array([ list(word) for word in a ])

However, if a has words of unequal length (e.g. ['snakes','on','a','plane']), what do you want to do with the shorter words? You could pad them with spaces to the longest word:

wid = max(len(w) for w in a)
b = np.array([ list(w.center(wid)) for w in a])

Which the string.center(width) pads with spaces, centering the string. You could also use rjust or ljust (see string docs).

这篇关于如何在numpy中创建字符数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆