Python访问MongoDB,并且转换成Dataframe的方法

yipeiwu_com6年前Python基础

如下所示:

#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2018/7/13 11:10
# @Author : baoshan
# @Site : 
# @File : pandans_pymongo.py
# @Software: PyCharm Community Edition

import pymongo
import pandas as pd


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 = pymongo.MongoClient(mongo_uri)
 else:
  conn = pymongo.MongoClient(host, port)

 return conn[db]


def read_mongo(db, collection, query={}, host='test43', 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).limit(10)

 # Expand the cursor and construct the DataFrame
 df = pd.DataFrame(list(cursor))
 df.to_csv("abc.csv", encoding="utf_8_sig") # 处理中文乱码问题

 if no_id:
  del df['_id']

 return df


read_mongo(db='service', collection='trace_log_regular', query={}, host='xxx', port=27017, username="xxx", password="xxx")

小结:

1. 解决了pymongo访问MongoDB的问题

2. 解决了查询的数据转成dataframe的问题

3. 解决了dataframe写入到csv的问题

4. 解决了中文乱码问题。

以上这篇Python访问MongoDB,并且转换成Dataframe的方法就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持【听图阁-专注于Python设计】。

相关文章

Python编程中运用闭包时所需要注意的一些地方

写下这篇博客,起源于Tornado邮件群组的这个问题how to use outer variable in inner method,这里面老外的回答很有参考价值,关键点基本都说到了。...

解析Python3中的Import

Python import的搜索路径 import的搜索路径为: 搜索「内置模块」(built-in module) 搜索 sys.path 中的路径 而sys.path在...

对pycharm 修改程序运行所需内存详解

编辑PyCharm安装目录下PyCharm 4.5.3\bin下的pycharm.exe.vmoptions文件, 如下 -server -Xms128m -Xmx512m -XX:...

从Python的源码浅要剖析Python的内存管理

从Python的源码浅要剖析Python的内存管理

Python 的内存管理架构(Objects/obmalloc.c): 复制代码 代码如下:     _____   ______&nb...

最近Python有点火? 给你7个学习它的理由!

最近Python有点火? 给你7个学习它的理由!

Python 是一门更注重可读性和效率的语言,尤其是相较于 Java,PHP 以及 C++ 这样的语言,它的这两个优势让其在开发者中大受欢迎。 诚然,它有点老了,但仍是80后啊 —— 至...