Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

str() method on numpy array and back

Tags:

Is there any built-in method to get back numpy array after applying str() method, for example,

import numpy as np
a = np.array([[1.1, 2.2, 3.3], [4.4, 5.5, 6.6]])
a_str = str(a)

#to get back a?
a = some_method(a_str).

Following two methods don't work:

from ast import literal_eval
a = literal_eval(a_str)  # Error

import numpy as np
a = np.fromstring(a_str)  # Error

Update 1: Unfortunatelly i have very big data already converted with str() method so I connot reconvert it with some other method.

like image 249
Oli Avatar asked Aug 29 '18 09:08

Oli


2 Answers

The main issues seem to be separators and newlines characters. You can use np.array2string and str.splitlines to resolve them:

import numpy as np
from ast import literal_eval

a = np.array([[1.1, 2.2, 3.3], [4.4, 5.5, 6.6]])

a_str = ''.join(np.array2string(a, separator=',').splitlines())

# '[[ 1.1, 2.2, 3.3], [ 4.4, 5.5, 6.6]]'

b = np.array(literal_eval(a_str))

# array([[ 1.1,  2.2,  3.3],
#        [ 4.4,  5.5,  6.6]])

Note that without any arguments np.array2string behaves like str.


If your string is given and unavoidable, you can use this hacky method:

a_str = str(a)
res = np.array(literal_eval(''.join(a_str.replace('\n', ' ').replace('  ', ','))))

array([[ 1.1,  2.2,  3.3],
       [ 4.4,  5.5,  6.6]])

As per @hpaulj's comment, one benefit of np.array2string is ability to specify threshold. For example, consider a string representation of x = np.arange(10000).

  • str(x) will return ellipsis, e.g. '[ 0 1 2 ..., 9997 9998 9999]'
  • np.array2string(x, threshold=11e3) will return the complete string
like image 90
jpp Avatar answered Sep 28 '22 17:09

jpp


You can do that with repr:

import numpy as np
a = np.array([[1.1, 2.2, 3.3], [4.4, 5.5, 6.6]])
a_str = repr(a)
b = eval("np." + repr(a))
print(repr(a))
print(repr(b))
like image 22
Maxim Egorushkin Avatar answered Sep 28 '22 17:09

Maxim Egorushkin