本文介紹了在mongodb中保存numpy數(shù)組的處理方法,對(duì)大家解決問題具有一定的參考價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)吧!
問題描述
我有幾個(gè) MongoDB 文檔,其中一個(gè)字段最好表示為矩陣(numpy 數(shù)組).我想將此文檔保存到 MongoDB,我該怎么做?
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?
{
'name' : 'subject1',
'image_name' : 'blah/foo.png',
'feature1' : np.array(...)
}
推薦答案
對(duì)于一維 numpy 數(shù)組,可以使用列表:
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'] )
對(duì)于多維數(shù)據(jù),我相信你需要使用pickle和pymongo.binary.Binary:
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'] )
這篇關(guān)于在mongodb中保存numpy數(shù)組的文章就介紹到這了,希望我們推薦的答案對(duì)大家有所幫助,也希望大家多多支持html5模板網(wǎng)!
【網(wǎng)站聲明】本站部分內(nèi)容來源于互聯(lián)網(wǎng),旨在幫助大家更快的解決問題,如果有圖片或者內(nèi)容侵犯了您的權(quán)益,請(qǐng)聯(lián)系我們刪除處理,感謝您的支持!