반응형
mongodb의 컬렉션에 분석해야 할 많은 양의 데이터가 있습니다. 해당 데이터를 Pandas로 어떻게 가져 옵니까?
나는 pandas와 numpy를 처음 사용합니다.
편집하다: mongodb 컬렉션에는 날짜 및 시간 태그가 지정된 센서 값이 포함됩니다. 센서 값은 float 데이터 유형입니다.
샘플 데이터 :
{
"_cls" : "SensorReport",
"_id" : ObjectId("515a963b78f6a035d9fa531b"),
"_types" : [
"SensorReport"
],
"Readings" : [
{
"a" : 0.958069536790466,
"_types" : [
"Reading"
],
"ReadingUpdatedDate" : ISODate("2013-04-02T08:26:35.297Z"),
"b" : 6.296118156595,
"_cls" : "Reading"
},
{
"a" : 0.95574014778624,
"_types" : [
"Reading"
],
"ReadingUpdatedDate" : ISODate("2013-04-02T08:27:09.963Z"),
"b" : 6.29651468650064,
"_cls" : "Reading"
},
{
"a" : 0.953648289182713,
"_types" : [
"Reading"
],
"ReadingUpdatedDate" : ISODate("2013-04-02T08:27:37.545Z"),
"b" : 7.29679823731148,
"_cls" : "Reading"
},
{
"a" : 0.955931884300997,
"_types" : [
"Reading"
],
"ReadingUpdatedDate" : ISODate("2013-04-02T08:28:21.369Z"),
"b" : 6.29642922525632,
"_cls" : "Reading"
},
{
"a" : 0.95821381,
"_types" : [
"Reading"
],
"ReadingUpdatedDate" : ISODate("2013-04-02T08:41:20.801Z"),
"b" : 7.28956613,
"_cls" : "Reading"
},
{
"a" : 4.95821335,
"_types" : [
"Reading"
],
"ReadingUpdatedDate" : ISODate("2013-04-02T08:41:36.931Z"),
"b" : 6.28956574,
"_cls" : "Reading"
},
{
"a" : 9.95821341,
"_types" : [
"Reading"
],
"ReadingUpdatedDate" : ISODate("2013-04-02T08:42:09.971Z"),
"b" : 0.28956488,
"_cls" : "Reading"
},
{
"a" : 1.95667927,
"_types" : [
"Reading"
],
"ReadingUpdatedDate" : ISODate("2013-04-02T08:43:55.463Z"),
"b" : 0.29115237,
"_cls" : "Reading"
}
],
"latestReportTime" : ISODate("2013-04-02T08:43:55.463Z"),
"sensorName" : "56847890-0",
"reportCount" : 8
}
해결 방법
pymongo
가 도움을 줄 수 있습니다. 다음은 제가 사용중인 코드입니다.
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
참조 페이지 https://stackoverflow.com/questions/16249736
반응형
'파이썬' 카테고리의 다른 글
파이썬 아름다운 수프와 레를 사용하여 특정 텍스트를 포함하는 특정 클래스로 스팬을 찾는 방법은 무엇입니까? (0) | 2021.01.18 |
---|---|
파이썬 목록을 n 그룹으로 분할하는 다른 방법 (0) | 2021.01.18 |
파이썬 Python을 사용하여 국가 이름을 ISO 3166-1 alpha-2 값으로 변환하는 방법 (0) | 2021.01.18 |
파이썬 Django에서 로컬 및 프로덕션 설정을 관리하는 방법은 무엇입니까? (0) | 2021.01.18 |
파이썬 ImportError : 'requests'라는 모듈이 없습니다. (0) | 2021.01.17 |
댓글