2016-08-22 121 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

相關問題