1. 程式人生 > >在mongodb中儲存numpy陣列

在mongodb中儲存numpy陣列

原文連結:https://cloud.tencent.com/developer/ask/32026

對於一維numpy陣列,可以使用列表:

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

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

對於多維陣列,你需要使用pickle和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'] )