【问题标题】:Extracting information from multiple JSON files to single CSV file in python在python中从多个JSON文件中提取信息到单个CSV文件
【发布时间】:2016-12-29 09:54:12
【问题描述】:

我有一个包含多个字典的 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 文件中。我当然可以手动执行此操作,但这非常繁琐。我知道 DictWriter,但它似乎只适用于单个词典。我也知道字典可以串联,但是会出现问题,因为所有字典都有相同的键。

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

【问题讨论】:

    标签: python json python-2.7 csv pandas


    【解决方案1】:

    您可以整理数据,以便每一行都是一个独特的观察结果。

    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)
    

    【讨论】:

    • 您可能应该澄清您正在使用pandas 库。
    • 谢谢。如果我想将四行合二为一,我应该反复旋转吗?
    • @wwl 您希望结果是什么样的?
    • 列应该是:team1player1item1, team1player1totalscore, ..., team1player2item1, team1player2totalscore, ..., team2player1item1, team2player1totalscore, ...
    • 我相信你可以通过df.T转置数据帧
    猜你喜欢
    • 2021-11-22
    • 1970-01-01
    • 2017-01-12
    • 1970-01-01
    • 2013-08-07
    • 2020-11-30
    • 2021-11-28
    • 1970-01-01
    • 2021-09-10
    相关资源
    最近更新 更多