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

前端 未结 7 643
北恋
北恋 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:17

    This is a fast way to encode the array, the array shape and the array dtype:

    def numpy_to_bytes(arr: np.array) -> str:
        arr_dtype = bytearray(str(arr.dtype), 'utf-8')
        arr_shape = bytearray(','.join([str(a) for a in arr.shape]), 'utf-8')
        sep = bytearray('|', 'utf-8')
        arr_bytes = arr.ravel().tobytes()
        to_return = arr_dtype + sep + arr_shape + sep + arr_bytes
        return to_return
    
    def bytes_to_numpy(serialized_arr: str) -> np.array:
        sep = '|'.encode('utf-8')
        i_0 = serialized_arr.find(sep)
        i_1 = serialized_arr.find(sep, i_0 + 1)
        arr_dtype = serialized_arr[:i_0].decode('utf-8')
        arr_shape = tuple([int(a) for a in serialized_arr[i_0 + 1:i_1].decode('utf-8').split(',')])
        arr_str = serialized_arr[i_1 + 1:]
        arr = np.frombuffer(arr_str, dtype = arr_dtype).reshape(arr_shape)
        return arr
    

    To use the functions:

    a = np.ones((23, 23), dtype = 'int')
    a_b = numpy_to_bytes(a)
    a1 = bytes_to_numpy(a_b)
    np.array_equal(a, a1) and a.shape == a1.shape and a.dtype == a1.dtype
    

提交回复
热议问题