0

Converting string to numpy array

Given a string abcxyz, I want it to return a numpy array like:

array(["a", "b", "c", "x", "y", "z"]). 

I have tried fromstring

Bingrid = np.fromstring(elements, dtype=str) 

but it returns

ValueError: Zero-valued itemsize.

Barmar
  • 741,623
  • 53
  • 500
  • 612
xyzf
  • 3
  • 2

5 Answers5

1

Just in case; if you do not want to convert into a list:

np.fromiter('abcxyz',(str,16))
#array(['a', 'b', 'c', 'x', 'y', 'z'], dtype='<U16')
Talha Tayyab
  • 8,111
  • 25
  • 27
  • 44
0

Use list().

import numpy as np
s = "abcxyz"
print(np.array(list(s)))

Output:

['a' 'b' 'c' 'x' 'y' 'z']
Nick ODell
  • 15,465
  • 3
  • 32
  • 66
0

How about np.array(list("abcxyz")) ? No need for any special methods.

hobbs
  • 223,387
  • 19
  • 210
  • 288
0

Convert to a list, then to an array:

import numpy as np
Bingrid = np.array(list("abcxyz"))
Joooeey
  • 3,394
  • 1
  • 35
  • 49
0

This one works for me:

import numpy as np
mystr = "100110"
res =  np.array(list(mystr))
print(res)

Possible duplicate: Convert string to numpy array

Ted Vu
  • 29
  • 1
  • 5