2016-08-22 83 views
2

提取infromation我有多个词典一个JSON文件:从多个JSON文件到一个CSV文件在python

{"team1participants": 
[ { 
     "stats": { 
      "item1": 3153, 
      "totalScore": 0, 
      ... 
     } 
    }, 
    { 
     "stats": { 
      "item1": 2123, 
      "totalScore": 5, 
      ... 
     } 
    }, 
    { 
     "stats": { 
      "item1": 1253, 
      "totalScore": 1, 
      ... 
     } 
    } 
], 
"team2participants": 
[ { 
     "stats": { 
      "item1": 1853, 
      "totalScore": 2, 
      ... 
     } 
    }, 
    { 
     "stats": { 
      "item1": 21523, 
      "totalScore": 5, 
      ... 
     } 
    }, 
    { 
     "stats": { 
      "item1": 12503, 
      "totalScore": 1, 
      ... 
     } 
    } 
] 
} 

在换句话说,JSON有多个按键。每个密钥都有一个包含个人参与者统计的列表。

我有很多这样的JSON文件,我想将它解压缩到一个CSV文件。我当然可以手动做到这一点,但这是非常乏味的。我知道DictWriter,但它似乎只适用于单个字典。我也知道词典可以连接在一起,但它会有问题,因为所有词典都有相同的键。

如何有效地将其提取到CSV文件?

回答

2

您可以使您的数据整洁,使每一行是一个独特的观察。

teams = [] 
items = [] 
scores = [] 
for team in d: 
    for item in d[team]: 
     teams.append(team) 
     items.append(item['stats']['item1']) 
     scores.append(item['stats']['totalScore']) 


# Using Pandas. 
import pandas as pd 

df = pd.DataFrame({'team': teams, 'item': items, 'score': scores}) 
>>> df 
    item score    team 
0 1853  2 team2participants 
1 21523  5 team2participants 
2 12503  1 team2participants 
3 3153  0 team1participants 
4 2123  5 team1participants 
5 1253  1 team1participants 

你也可以使用列表理解而不是循环。

results = [[team, item['stats']['item1'], item['stats']['totalScore']] 
      for team in d for item in d[team]] 
df = pd.DataFrame(results, columns=['team', 'item', 'score']) 

然后,您可以做一个透视表,例如:

>>> df.pivot_table(values='score ', index='team ', columns='item', aggfunc='sum').fillna(0) 
item    1253 1853 2123 3153 12503 21523 
team              
team1participants  1  0  5  0  0  0 
team2participants  0  2  0  0  1  5 

而且,现在它是一个数据帧,很容易将其保存为CSV。

df.to_csv(my_file_name.csv) 
+2

您应该澄清一下,您正在使用'pandas'库。 –

+0

谢谢。如果我想将四行合成一个,我应该重复枢轴吗? – wwl

+0

@wwl您希望结果如何? – Alexander

相关问题