zoukankan      html  css  js  c++  java
  • 在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
    

      

  • 相关阅读:
    Swift:属性观察器
    swift:谈谈swift几种常见属性的区别
    iOS:崩溃统计工具Crashlytics的使用
    【互动出版网】2013双11全场科技图书六折包邮
    【互动出版网】11.11购物狂欢节重磅大促,免费领万千优惠券
    C#编程兵书
    C++编程兵书
    HTML+CSS网站开发兵书
    Java编程兵书
    网络运维与管理2013超值精华本
  • 原文地址:https://www.cnblogs.com/snaildev/p/8907952.html
Copyright © 2011-2022 走看看