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

前端 未结 7 650
北恋
北恋 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:31

    I know, I am late but here is the correct way of doing it. using base64. This technique will convert the array to string.

    import base64
    import numpy as np
    random_array = np.random.randn(32,32)
    string_repr = base64.binascii.b2a_base64(random_array).decode("ascii")
    array = np.frombuffer(base64.binascii.a2b_base64(string_repr.encode("ascii"))) 
    

    For array to string

    Convert binary data to a line of ASCII characters in base64 coding and decode to ASCII to get string repr.

    For string to array

    First, encode the string in ASCII format then Convert a block of base64 data back to binary and return the binary data.

提交回复
热议问题