Skip to content Skip to sidebar Skip to footer

Convert String Containg Array Of Floats To Numpy Array

I have a numpy array of floats that I wish to convert to a string to transmit via JSON: import numpy as np #Create an array of float arrays numbers = np.array([[1.0, 2.0],[3.0,4.0]

Solution 1:

I think the problem is that the format is not quite the formats that numpy is expecting, but if the string is not too huge:

In [39]: eval('np.array([%s])' % '[1. 2.],[3. 4.],[5. 6.]'.replace(' ', ','))
Out[39]: 
array([[1., 2.],
       [3., 4.],
       [5., 6.]])

Be aware if the string is very long you might run into issues: Why is there a length limit to python's eval?

Solution 2:

Maybe you could modify your "numbers_to_string_commas" a little to make rereading easier. Here's another solution:

a=np.matrix(numbers_to_string_commas.replace(',',' ').replace('] [',';')[1:-1])
>>> a
matrix([[ 1.,  2.],
        [ 3.,  4.],
        [ 5.,  6.]])

This seems to do what you wanted.

Post a Comment for "Convert String Containg Array Of Floats To Numpy Array"