Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert string to numpy array

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?

like image 922
Am1rr3zA Avatar asked Jan 29 '15 05:01

Am1rr3zA


People also ask

How do I convert a string to an array of arrays in Python?

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.

Can we use strings in NumPy array?

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.


2 Answers

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] 
like image 75
dragon2fly Avatar answered Oct 04 '22 17:10

dragon2fly


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.

like image 32
grc Avatar answered Oct 04 '22 15:10

grc