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.

2
  • Try: numpy.array(list("abcxyz")) Commented May 26, 2023 at 20:18
  • fromstring() is for parsing a delimited list, like a CSV. Commented May 26, 2023 at 20:19

5 Answers 5

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')
Sign up to request clarification or add additional context in comments.

Comments

0

Use list().

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

Output:

['a' 'b' 'c' 'x' 'y' 'z']

Comments

0

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

Comments

0

Convert to a list, then to an array:

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

Comments

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.