2016-07-27 68 views
2

也許有人可以幫助我。我試圖平以下IST爲大熊貓數據幀:從嵌套json列表中拼合熊貓DataFrame

[{u'_id': u'2', 
    u'_index': u'list', 
    u'_score': 1.4142135, 
    u'_source': {u'name': u'name3'}, 
    u'_type': u'doc'}, 
{u'_id': u'5', 
    u'_index': u'list', 
    u'_score': 1.4142135, 
    u'_source': {u'dat': u'2016-12-12', u'name': u'name2'}, 
    u'_type': u'doc'}, 
{u'_id': u'1', 
    u'_index': u'list', 
    u'_score': 1.4142135, 
    u'_source': {u'name': u'name1'}, 
    u'_type': u'doc'}] 

結果應該是這樣的:

|_id | _index | _score | name | dat  | _type | 
------------------------------------------------------ 
|1  |list |1.4142..| name1| nan  | doc | 
|2  |list |1.4142..| name3| nan  | doc | 
|3  |list |1.4142..| name1| 2016-12-12 | doc | 

但所有我試圖做的是不可能得到想要的結果。 我以前是這樣的:

df = pd.concat(map(pd.DataFrame.from_dict, res['hits']['hits']), axis=1)['_source'].T 

但後來我鬆散的類型至極是_source領域之外。 我也試圖與

test = pd.DataFrame(list) 
for index, row in test.iterrows(): 
    test.loc[index,'d'] = 

工作,但我不知道如何來使用領域_source並追加到原始數據幀的地步。

有人有一個想法如何去成爲期望的結果?

回答

3

使用json_normalize

from pandas.io.json import json_normalize 

df = json_normalize(data) 
print (df) 
    _id _index _score _source.dat _source.name _type 
0 2 list 1.414214   NaN  name3 doc 
1 5 list 1.414214 2016-12-12  name2 doc 
2 1 list 1.414214   NaN  name1 doc