Skip to content
Advertisement

How can a string representation of a NumPy array be converted to a NumPy array?

The function numpy.array_repr can be used to create a string representation of a NumPy array. How can a string representation of a NumPy array be converted to a NumPy array?

Let’s say the string representation is as follows:

array([-0.00470366,  0.00253503,  0.00306358, -0.00354276,  0.00743946,
       -0.00313205,  0.00318478,  0.0074185 , -0.00312317,  0.00127158,
        0.00249559,  0.00140165,  0.00053142, -0.00685036,  0.01367841,
       -0.0024475 ,  0.00120164, -0.00665447,  0.00145064,  0.00128595,
       -0.00094848,  0.0028348 , -0.01571732, -0.00150459,  0.00502642,
       -0.00259262,  0.00222584,  0.00431143, -0.00379282,  0.00630756,
        0.001324  , -0.00420992, -0.00808643,  0.00180546,  0.00586163,
        0.00177767, -0.0011724 , -0.00270304,  0.00505948,  0.00627092,
       -0.00496326,  0.00460142, -0.00177408, -0.00066973,  0.00226059,
        0.00501507, -0.00261056, -0.00617777,  0.00269939, -0.01023268,
        0.00338639,  0.00483614,  0.00086805,  0.00041314, -0.0099909 ,
        0.00356182, -0.00788026,  0.00245763,  0.00371736,  0.00343493,
       -0.00037843, -0.0013632 , -0.00210518,  0.00362144,  0.00061659,
       -0.0008905 , -0.01148648, -0.00292173, -0.00206425,  0.00606295,
        0.0041656 , -0.00407792,  0.00026893,  0.00078469,  0.00186181,
        0.00067565, -0.00811732,  0.00257632,  0.00177333, -0.00602056,
        0.00853466,  0.0016037 ,  0.00094006, -0.00018953, -0.00408413,
       -0.00994886,  0.01268128,  0.0080336 ,  0.00546633,  0.00372206,
        0.00228082,  0.00445107,  0.00236268,  0.01059031, -0.00106609,
       -0.00055983,  0.00371333,  0.0004037 ,  0.00632817,  0.00145055], dtype=float32)

How could this be converted to a NumPy array?

Advertisement

Answer

eval is the easiest, probably. It evaluates a given string as if it were code.

from numpy import array, all
arr_1 = array([1,2,3])
arr_string = repr(arr_1)
arr_2 = eval(arr_string)

all(arr_1 == arr_2) # True

See also documentation on eval: https://docs.python.org/2/library/functions.html#eval

User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement