Convert a numpy.ndarray to string(or bytes) and convert it back to numpy.ndarray

前端 未结 7 644
北恋
北恋 2020-12-08 09:52

I\'m having a little trouble here,

I\'m trying to convert a numpy.ndarray to string, I\'ve already done that like this:

randomArray.tostring()
         


        
7条回答
  •  南方客
    南方客 (楼主)
    2020-12-08 10:13

    You can use the fromstring() method for this:

    arr = np.array([1, 2, 3, 4, 5, 6])
    ts = arr.tostring()
    print(np.fromstring(ts, dtype=int))
    
    >>> [1 2 3 4 5 6]
    

    Sorry for the short answer, not enough points for commenting. Remember to state the data types or you'll end up in a world of pain.

    Note on fromstring from numpy 1.14 onwards:

    sep : str, optional

    The string separating numbers in the data; extra whitespace between elements is also ignored.

    Deprecated since version 1.14: Passing sep='', the default, is deprecated since it will trigger the deprecated binary mode of this function. This mode interprets string as binary bytes, rather than ASCII text with decimal numbers, an operation which is better spelt frombuffer(string, dtype, count). If string contains unicode text, the binary mode of fromstring will first encode it into bytes using either utf-8 (python 3) or the default encoding (python 2), neither of which produce sane results.

提交回复
热议问题