2013-07-23 29 views
7

Tôi mới làm quen với gấu trúc (vâng, với mọi thứ "lập trình" ...), nhưng đã được khuyến khích dùng thử. Tôi có một cơ sở dữ liệu mongodb - "kiểm tra" - với một bộ sưu tập được gọi là "tweets". tôi truy cập vào cơ sở dữ liệu trong ipython:Làm cách nào để tải dữ liệu từ bộ sưu tập mongodb vào DataFrame của gấu trúc?

import sys 
import pymongo 
from pymongo import Connection 
connection = Connection() 
db = connection.test 
tweets = db.tweets 

cấu trúc tài liệu văn bản trong tweet như sau:

entities': {u'hashtags': [], 
    u'symbols': [], 
    u'urls': [], 
    u'user_mentions': []}, 
u'favorite_count': 0, 
u'favorited': False, 
u'filter_level': u'medium', 
u'geo': {u'coordinates': [placeholder coordinate, -placeholder coordinate], u'type': u'Point'}, 
u'id': 349223842700472320L, 
u'id_str': u'349223842700472320', 
u'in_reply_to_screen_name': None, 
u'in_reply_to_status_id': None, 
u'in_reply_to_status_id_str': None, 
u'in_reply_to_user_id': None, 
u'in_reply_to_user_id_str': None, 
u'lang': u'en', 
u'place': {u'attributes': {}, 
    u'bounding_box': {u'coordinates': [[[placeholder coordinate, placeholder coordinate], 
    [-placeholder coordinate, placeholder coordinate], 
    [-placeholder coordinate, placeholder coordinate], 
    [-placeholder coordinate, placeholder coordinate]]], 
    u'type': u'Polygon'}, 
    u'country': u'placeholder country', 
    u'country_code': u'example', 
    u'full_name': u'name, xx', 
    u'id': u'user id', 
    u'name': u'name', 
    u'place_type': u'city', 
    u'url': u'http://api.twitter.com/1/geo/id/1820d77fb3f65055.json'}, 
u'retweet_count': 0, 
u'retweeted': False, 
u'source': u'<a href="http://twitter.com/download/iphone" rel="nofollow">Twitter for iPhone</a>', 
u'text': u'example text', 
u'truncated': False, 
u'user': {u'contributors_enabled': False, 
    u'created_at': u'Sat Jan 22 13:42:59 +0000 2011', 
    u'default_profile': False, 
    u'default_profile_image': False, 
    u'description': u'example description', 
    u'favourites_count': 100, 
    u'follow_request_sent': None, 
    u'followers_count': 100, 
    u'following': None, 
    u'friends_count': 100, 
    u'geo_enabled': True, 
    u'id': placeholder_id, 
    u'id_str': u'placeholder_id', 
    u'is_translator': False, 
    u'lang': u'en', 
    u'listed_count': 0, 
    u'location': u'example place', 
    u'name': u'example name', 
    u'notifications': None, 
    u'profile_background_color': u'000000', 
    u'profile_background_image_url': u'http://a0.twimg.com/images/themes/theme19/bg.gif', 
    u'profile_background_image_url_https': u'https://si0.twimg.com/images/themes/theme19/bg.gif', 
    u'profile_background_tile': False, 
    u'profile_banner_url': u'https://pbs.twimg.com/profile_banners/241527685/1363314054', 
    u'profile_image_url':  u'http://a0.twimg.com/profile_images/378800000038841219/8a71d0776da0c48dcc4ef6fee9f78880_normal.jpeg', 
    u'profile_image_url_https':  u'https://si0.twimg.com/profile_images/378800000038841219/8a71d0776da0c48dcc4ef6fee9f78880_normal.jpeg', 
    u'profile_link_color': u'000000', 
    u'profile_sidebar_border_color': u'FFFFFF', 
    u'profile_sidebar_fill_color': u'000000', 
    u'profile_text_color': u'000000', 
    u'profile_use_background_image': False, 
    u'protected': False, 
    u'screen_name': placeholder screen_name', 
    u'statuses_count': xxxx, 
    u'time_zone': u'placeholder time_zone', 
    u'url': None, 
    u'utc_offset': -21600, 
    u'verified': False}} 

Bây giờ, theo như tôi hiểu, cấu trúc dữ liệu chính gấu trúc - một spreadsheet- như bảng - được gọi là DataFrame. Làm cách nào để tải dữ liệu từ bộ sưu tập "tweets" của tôi vào DataFrame của gấu trúc? Và làm thế nào tôi có thể truy vấn một subdocument trong cơ sở dữ liệu?

+0

Có phải là một cách để làm điều này bằng read_json, đó sẽ là effecient hơn (đặc biệt đối với các tập dữ liệu lớn). –

Trả lời

16

Hiểu con trỏ bạn nhận được từ các MongoDB trước khi đi qua nó để DataFrame

import pandas as pd 
df = pd.DataFrame(list(tweets.find())) 
+0

Tuyệt vời, bằng cách chuyển "df" các tài liệu của bộ sưu tập được đưa lên trong cột dữ liệu. Tuy nhiên, tôi cần truy vấn một subdocument - "hashtags.text" - trong một trong các tài liệu, "các thực thể". Bất kỳ ý tưởng làm thế nào tôi có thể làm điều này từ bên trong gấu trúc? – user2161725

+0

Bạn có thể hiển thị một số ví dụ cho tài liệu của mình để tôi có thể giúp bạn không? – waitingkuo

+0

Bạn cần gì? Trường hashtags? – waitingkuo

3

Bạn có thể tải dữ liệu MongoDB của bạn để gấu trúc DataFame sử dụng mã này. Nó làm việc cho tôi. Hy vọng cho bạn quá.

import pymongo 
import pandas as pd 
from pymongo import Connection 
connection = Connection() 
db = connection.database_name 
input_data = db.collection_name 
data = pd.DataFrame(list(input_data.find())) 
+0

ở đây chúng tôi được đề cập đến tên bộ sưu tập. Nếu chúng tôi không muốn đề cập đến tên bộ sưu tập thì chúng tôi có thể lưu trữ tệp đó như thế nào? –

6

Nếu bạn có dữ liệu trong MongoDB như thế này:

[ 
    { 
     "name": "Adam", 
     "age": 27, 
     "address":{ 
      "number": 4, 
      "street": "Main Road", 
      "city": "Oxford" 
     } 
    }, 
    { 
     "name": "Steve", 
     "age": 32, 
     "address":{ 
      "number": 78, 
      "street": "High Street", 
      "city": "Cambridge" 
     } 
    } 
] 

Bạn có thể đặt các dữ liệu thẳng vào một dataframe như thế này:

from pandas import DataFrame 

df = DataFrame(list(db.collection_name.find({})) 

Và bạn sẽ nhận được kết quả này:

df.head() 

| | name | age | address             | 
|----|---------|------|-----------------------------------------------------------| 
| 1 | "Steve" | 27 | {"number": 4, "street": "Main Road", "city": "Oxford"} | 
| 2 | "Adam" | 32 | {"number": 78, "street": "High St", "city": "Cambridge"} | 

Tuy nhiên các subdocuments sẽ xuất hiện dưới dạng JSON bên trong ô subdocument. Nếu bạn muốn làm phẳng các đối tượng để các thuộc tính subdocument được hiển thị dưới dạng các ô riêng lẻ, bạn có thể sử dụng json_normalize mà không có bất kỳ tham số nào.

from pandas.io.json import json_normalize 

datapoints = list(db.collection_name.find({}) 

df = json_normalize(datapoints) 

df.head() 

này sẽ cung cấp cho các dataframe ở định dạng này:

| | name | age | address.number | address.street | address.city | 
|----|--------|------|----------------|----------------|--------------| 
| 1 | Thomas | 27 |  4   | "Main Road" | "Oxford"  | 
| 2 | Mary | 32 |  78   | "High St"  | "Cambridge" | 
+0

Nếu chúng ta không muốn đề cập đến tên bộ sưu tập thì làm thế nào để lấy dữ liệu cho tất cả các bộ sưu tập ?? –

Các vấn đề liên quan