在python中从多个JSON文件提取信息到单个CSV文件

2024-10-01 04:59:18 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个包含多个字典的JSON文件:

{"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文件。我当然可以手动完成,但这很乏味。我知道听写器,但它似乎只适用于单本词典。我也知道字典可以连接起来,但这会有问题,因为所有字典都有相同的键。在

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


Tags: 文件csv信息json列表字典stats手动
1条回答
网友
1楼 · 发布于 2024-10-01 04:59:18

您可以使数据整洁,这样每一行都是唯一的观察。在

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

你也可以使用列表理解来代替循环。在

^{pr2}$

然后可以创建透视表,例如:

>>> 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)

相关问题 更多 >