Harry Boy
Harry Boy

Reputation: 4777

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],[5.0,6.0]], dtype=np.float64)
print(numbers)
[[1. 2.]
 [3. 4.]
 [5. 6.]]

#Convert each row in the array to string and separate by a ','
numbers_to_string_commas = ','.join(str(number) for number in numbers)
print(numbers_to_string_commas)
[1. 2.],[3. 4.],[5. 6.]

Now I wish to convert this string back into the original numpy array. I have tried using the following but I have had no joy:

a = np.fromstring(numbers_to_string_commas, dtype=np.float64, sep=',')
print(a)
[]

How can I do this?

Upvotes: 0

Views: 279

Answers (2)

CT Zhu
CT Zhu

Reputation: 54390

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?

Upvotes: 1

Telschazz
Telschazz

Reputation: 11

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.

Upvotes: 1

Related Questions