How do I create character arrays in numpy?

后端 未结 3 874
[愿得一人]
[愿得一人] 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:07

    Actually, you can do this without any copies or list comprehensions in numpy (caveats about non-equal-length strings aside...). Just view it as a 1 character string array and reshape it:

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

    This yields:

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

    Generally speaking, though, I'd avoid using numpy arrays to store strings in most cases. There are cases where it's useful, but you're usually better off sticking to data structures that allow variable-length strings for, well, holding strings.

提交回复
热议问题