Convert string to numpy array

I have a string like mystr = "100110" (the actual size is much larger). I want to convert it to a numpy array, for example mynumpy = [1, 0, 0, 1, 1, 0], mynumpy.shape = (6,0) , I know that numpy has np.fromstring(mystr, dtype=int, sep='') , but the problem is that I cannot split my string into each digit, so numpy takes this as one number. any idea how to convert my string to a numpy array?

+6
source share
2 answers

list can help you with this.

 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 strings:

 print np.array(list(mystr), dtype=int) # [1 0 0 1 1 0] 
+16
source

You can read them as ASCII characters and then subtract 48 (ASCII value 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 can first convert the string to a list of integers:

 >>> np.array(map(int, "100110")) array([1, 0, 0, 1, 1, 0]) 

Change I did some quick calculations, and the first method is more than 100 times faster than converting it to a list.

+11
source

Source: https://habr.com/ru/post/981696/


All Articles