韩方奕,话说夏娃歌词,卡盟第一闻月卡盟刷钻
在使用Pandas进行数据处理的时候,我们通常从CSV或EXCEL中导入数据,但有的时候数据都存在数据库内,我们并没有现成的数据文件,这时候可以通过Pymongo这个库,从mongoDB中读取数据,然后载入到Pandas中,只需要简单的三步。
import pymongo import pandas as pd
client = pymongo.MongoClient('localhost',27017) db = client['Lottery'] pk10 = db['Pk10']
data = pd.DataFrame(list(pk10.find()))
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
如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复
python求numpy中array按列非零元素的平均值案例
网友评论