2015-11-25 55 views
0

我有一個JSON文件看起來像:JSON堆疊數據幀

[ 

     { 
     "id" : "abc", 
     "mood" : "happy", 
     "scores" : [ 
      10, 
      15, 
      20 
      ] 
     }, 
     { 
     "id" : "def", 
     "mood" : "happy", 
     "scores" : [ 
      103, 
      150, 
      200 
      ] 
     }, 
     { 
     "id" : "ghi", 
     "mood" : "sad", 
     "scores" : [ 
      1, 
      15, 
      20, 
      45, 
      600, 
      1400 
      ] 
     }, 
     { 
     "id" : "jkl", 
     "mood" : "sad", 
     "scores" : [ 
      10, 
      100, 
      1000, 
      10000 
      ] 
     } 

] 

我敢試圖得到了多層數據幀,看起來像:

id mood score 
0 abc happy 10 
1 abc happy 15 
2 abc happy 20 
3 def happy 103 
... 
14 jkl sad  10 
15 jkl sad  100 

但是,當我將JSON對象粘貼到數據框中時,我總是會得到一些變化:

example output

其中「分數」列是列表。我已經搜索了很長時間,很難找到一個例子,但無法弄清楚如何將列表解壓縮到我想要的格式。

對此提出建議?

+1

除了我的回答,[這個蘇答案(http://stackoverflow.com/questions/21160134/flatten-a -column-with-value-of-type-list-while-duplicating-the-other-columns-va)似乎可能是相關的。 – jme

回答

1

一種方法是讓在你的列表中的每個條目的數據幀,然後將它們連接起來:

>>> pd.concat([pd.DataFrame(d) for d in data]) 

這似乎是浪費,雖然,因爲你分配的內存塊,每個條目只是來連接他們到底。另外,您也可以定義一個發電機:

def iter_data(data): 
    for entry in data: 
     for score in entry['scores']: 
      yield entry['mood'], entry['id'], score 

這樣

>>> pd.DataFrame(iter_data(data)) 

    id mood scores 
0 abc happy  10 
1 abc happy  15 
2 abc happy  20 
0 def happy  103 
1 def happy  150 
2 def happy  200 
0 ghi sad  1 
1 ghi sad  15 
2 ghi sad  20 
3 ghi sad  45 
4 ghi sad  600 
5 ghi sad 1400 
0 jkl sad  10 
1 jkl sad  100 
2 jkl sad 1000 
3 jkl sad 10000 
+0

輝煌。謝謝。 –