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

后端 未结 2 1188
暗喜
暗喜 2021-01-23 00:46

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 Num

2条回答
  •  北海茫月
    2021-01-23 01:19

    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

提交回复
热议问题