程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

Mongodb saves and reads data in numpy and pandas formats

編輯:Python

about Numpy Formatted data :

  • Save with :Binary(pickle.dumps(array, protocol=2)), among array Namely ndarry Formatted array
  • Load with :pickle.loads(result['numpy'])

about Pandas Formatted data :

  • Save with :json.dumps(dataframe.to_dict('records'))
  • Load with :pd.DataFrame(json.loads(result['dataframe']))

Sample code

import pymongo
import numpy as np
import pandas as pd
import json
import pickle
from bson.binary import Binary
# Connect to database 
mongo_conn = pymongo.MongoClient(host='localhost', port=27017)
db = mongo_conn.get_database("test") # Specify database 
coll = db.get_collection("people") # Get the set 
# Structural data 
array = np.random.random(size=(5, 10)) # To save numpy Format data 
dataframe = pd.DataFrame(data=np.random.random(size=(10, 20))) # To save pandas dataframe Format data 
config_dict = {

'a': True,
'b': False,
'c': 3,
'd': ["a", "b", 3],
}
# Start saving 
coll.insert_one({
 # Insert 
'_id': ' test ',
'dataframe': json.dumps(dataframe.to_dict('records')),
"numpy": Binary(pickle.dumps(array, protocol=2)),
"config_dict": config_dict,
})
# Go back to 
result = coll.find_one({
"_id": " test "})
recover_dataframe = pd.DataFrame(json.loads(result['dataframe']))
recover_array = pickle.loads(result['numpy'])
recover_config_dict = result['config_dict']

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved