2015-11-25 53 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

辉煌。谢谢。 –