6

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.

2
  • 1
    Really, you should avoid this where possible. But I have updated with a solution which reverses str output. Commented Aug 29, 2018 at 10:11
  • Does that big data string include ellipsis (...)? Commented Aug 29, 2018 at 16:48

2 Answers 2

3

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
Sign up to request clarification or add additional context in comments.

2 Comments

The threshhold also limits the usefulness of str.
1

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))

2 Comments

@jpp ast.literal_eval is too safe to be useful.
@MaximEgorushkin @jpp i have updated the question, i cannot use repr() or other methods, question is specific by using only str() mehod.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.