Input:
mystr = "100110"
Desired output numpy array:
mynumpy == np.array([1, 0, 0, 1, 1, 0])
I have tried:
np.fromstring(mystr, dtype=int, sep='')
but the problem is I can't split my string to every digit of it, so numpy takes it as an one number. Any idea how to convert my string to numpy array?
To convert String to array in Python, use String. split() method. The String . split() method splits the String from the delimiter and returns the splitter elements as individual list items.
Starting from numpy 1.4, if one needs arrays of strings, it is recommended to use arrays of dtype object_ , string_ or unicode_ , and use the free functions in the numpy. char module for fast vectorized string operations.
list
may help you do that.
import numpy as np mystr = "100110" print np.array(list(mystr)) # ['1' '0' '0' '1' '1' '0']
If you want to get numbers instead of string:
print np.array(list(mystr), dtype=int) # [1 0 0 1 1 0]
You could read them as ASCII characters then subtract 48 (the ASCII value of 0
). This should be the fastest way for large strings.
>>> np.fromstring("100110", np.int8) - 48 array([1, 0, 0, 1, 1, 0], dtype=int8)
Alternatively, you could convert the string to a list of integers first:
>>> np.array(map(int, "100110")) array([1, 0, 0, 1, 1, 0])
Edit: I did some quick timing and the first method is over 100x faster than converting it to a list first.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With