How do I create character arrays in numpy?

后端 未结 3 876
[愿得一人]
[愿得一人] 2020-12-30 02:45

Say I have the following array:

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

I want this to turn into a numpy array b

3条回答
  •  没有蜡笔的小新
    2020-12-30 03:25

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

提交回复
热议问题