Saving numpy array in mongodb

后端 未结 5 1757
醉话见心
醉话见心 2020-12-23 12:01

I have a couple of MongoDB documents wherein one my the fields is best represented as a matrix (numpy array). I would like to save this document to MongoDB, how do I do this

5条回答
  •  醉话见心
    2020-12-23 12:35

    For a 1D numpy array, you can use lists:

    # serialize 1D array x
    record['feature1'] = x.tolist()
    
    # deserialize 1D array x
    x = np.fromiter( record['feature1'] )
    

    For multidimensional data, I believe you'll need to use pickle and pymongo.binary.Binary:

    # serialize 2D array y
    record['feature2'] = pymongo.binary.Binary( pickle.dumps( y, protocol=2) ) )
    
    # deserialize 2D array y
    y = pickle.loads( record['feature2'] )
    

提交回复
热议问题