在Pandas中直接加载MongoDB的数据

在使用Pandas进行数据处理的时候,我们通常从CSV或EXCEL中导入数据,但有的时候数据都存在数据库内,我们并没有现成的数据文件,这时候可以通过Pymongo这个库,从mongoDB中读取数据,然后载入到Pandas中,只需要简单的三步。

第一步,导入相关的模块: 

import pymongo
import pandas as pd

  

第二步,设置MongoDB连接信息:

client = pymongo.MongoClient('localhost',27017)
db  = client['Lottery']
pk10 = db['Pk10']

  

第三步,加载数据到Pandas中:

data = pd.DataFrame(list(pk10.find()))

  

删除mongodb中的_id字段

del data['_id']

 

选择需要显示的字段

data = data[['date','num1','num10']]
print(data)

这样就可以轻松地从MongoDB中读取数据到Pandas中进行数据分析了。

stackoverflow

import pandas as pd
from pymongo import MongoClient


def _connect_mongo(host, port, username, password, db):
    """ A util for making a connection to mongo """

    if username and password:
        mongo_uri = 'mongodb://%s:%s@%s:%s/%s' % (username, password, host, port, db)
        conn = MongoClient(mongo_uri)
    else:
        conn = MongoClient(host, port)


    return conn[db]


def read_mongo(db, collection, query={}, host='localhost', port=27017, username=None, password=None, no_id=True):
    """ Read from Mongo and Store into DataFrame """

    # Connect to MongoDB
    db = _connect_mongo(host=host, port=port, username=username, password=password, db=db)

    # Make a query to the specific DB and Collection
    cursor = db[collection].find(query)

    # Expand the cursor and construct the DataFrame
    df =  pd.DataFrame(list(cursor))

    # Delete the _id
    if no_id:
        del df['_id']

    return df

  

 

posted @ 2018-04-22 16:29  snailteam  阅读(12811)  评论(1编辑  收藏  举报