2016-04-26 16 views
0

mongodbグループ操作の結果をpandas DataFrameに読み込む便利な方法はありますか?ここでmongoのグループ結果がpandaのDataFrame

はMongoのクエリをグループ化するタイプだん:私はこれがそうデータフレームにロードしたい

[ 
    ... 
    { "_id" : { "country" : "US", "oem" : "mmm" }, "count" : 595 }, 
    ... 
] 

'$group': { 
     '_id': {'country': '$country', 'oem':'$oem'}, 
     'count': {'$sum': 1} 
    } 

これは、次のように見える辞書のリストとして戻ってきますcountryoemは自動的にインデックスになります。結果を再マッピングするのに手間がかかりません。すでにこれを処理できるPandas APIには何かがありますか?または、mongoのクエリを何らかの形で書き直して、pandas APIに面白い構造体を返すことができますか?

+0

あなたの予想される出力は何ですか? – styvane

+0

は、 'country'、' oem'と 'count'(オプションで' country'と 'oem'によってインデックス付けされた)の3つのカラムを持つデータフレームです。 –

答えて

0

あなたがjson_normalize()を使用することができます。

In [59]: l 
Out[59]: 
[{'_id': {'country': 'UA', 'oem': 'uuuu'}, 'count': 555}, 
{'_id': {'country': 'US', 'oem': 'aaaa'}, 'count': 595}, 
{'_id': {'country': 'DE', 'oem': 'bbbb'}, 'count': 777}] 

In [60]: from pandas.io.json import json_normalize 

In [61]: l 
Out[61]: 
[{'_id': {'country': 'UA', 'oem': 'uuuu'}, 'count': 555}, 
{'_id': {'country': 'US', 'oem': 'aaaa'}, 'count': 595}, 
{'_id': {'country': 'DE', 'oem': 'bbbb'}, 'count': 777}] 

In [62]: json_normalize(l) 
Out[62]: 
    _id.country _id.oem count 
0   UA uuuu 555 
1   US aaaa 595 
2   DE bbbb 777 

セットアップ:

l = [ 
    { "_id" : { "country" : "UA", "oem" : "uuuu" }, "count" : 555 }, 
    { "_id" : { "country" : "US", "oem" : "aaaa" }, "count" : 595 }, 
    { "_id" : { "country" : "DE", "oem" : "bbbb" }, "count" : 777 }, 
] 
関連する問題