0

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?

Harry Boy
  • 4,159
  • 17
  • 71
  • 122
  • 1
    You might search on `numpy` and `json`, but I'd suggest doing `numbers.tolist()`, and encoding that (nested) list with `json`. The reverse is a `np.array(json.loads(...))`. `tolist` is a fast, and `json` handles lists of numbers quite well. – hpaulj Sep 10 '19 at 18:01

2 Answers2

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?

Community
  • 1
  • 1
CT Zhu
  • 52,648
  • 17
  • 120
  • 133
  • Thanks, How many numbers is too huge? And what problems could arise? – Harry Boy Sep 11 '19 at 09:22
  • Nothing really other than the size of big string. Storing numerical data in string is often less efficient than storing them in some binary format. You only need to be concerned if it is very big, see edit and the link added. – CT Zhu Sep 11 '19 at 23:16
1

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.

Telschazz
  • 11
  • 4