【问题标题】:Nested JSON and Pandas嵌套的 JSON 和 Pandas
【发布时间】:2021-08-13 00:44:10
【问题描述】:

我有一个如下所示的嵌套 JSON 文件(许多对象中的前 2 个):

{
"Abaddon the Despoiler": {
    "Abaddon the Despoiler": {
        "model_count": "1",
        "points_value": "220\u2022",
        "movement": "6\"",
        "weapon_skill": "2+",
        "ballistic_skill": "2+",
        "strength": "5",
        "toughness": "5",
        "wounds": "8",
        "attacks": "6",
        "leadership": "10",
        "save": "2+"
    }
},
"Chaos Lord": {
    "Chaos Lord": {
        "model_count": "1",
        "points_value": "80",
        "movement": "6\"",
        "weapon_skill": "2+",
        "ballistic_skill": "2+",
        "strength": "4",
        "toughness": "4",
        "wounds": "5",
        "attacks": "4",
        "leadership": "9",
        "save": "3+"
    }
},

我想将其转换为如下所示的数据框:

unit model_count points_value movement weapon_skill ballistic_skill strength toughness wounds attacks leadership save
Abaddon the Despoiler 1 220\u2022 6" 2+ 2+ 5 5 8 6 10 +2
Chaos Lord 1 80 6" 2+ 2+ 4 4 5 4 9 +3

我认为解决方案是使用 pandas json_normalize()

    #load json object
with open('./archive/chaos-space-marines.json') as f:
    d = json.load(f)

nycphil = pd.json_normalize(d)

nycphil.head(3)

但是,当我执行以下操作时,我得到一个 1 行 x 115 列的数据框,其列名如下

Abaddon the Despoiler.Abaddon the Despoiler.model_count

Abaddon the Despoiler.Abaddon the Despoiler.points_value

Abaddon the Despoiler.Abaddon the Despoiler.movement    

Abaddon the Despoiler.Abaddon the Despoiler.weapon_skill

有什么想法吗?

【问题讨论】:

    标签: python pandas json-normalize


    【解决方案1】:

    我建议使用list-comprehension 来读取您的dict:

    d = {'Abaddon the Despoiler': {'Abaddon the Despoiler': {'model_count': '1', 'points_value': '220•', 'movement': '6"', 'weapon_skill': '2+', 'ballistic_skill': '2+', 'strength': '5', 'toughness': '5', 'wounds': '8', 'attacks': '6', 'leadership': '10', 'save': '2+'}}, 
         'Chaos Lord':            {'Chaos Lord':            {'model_count': '1', 'points_value': '80','movement': '6"', 'weapon_skill': '2+', 'ballistic_skill': '2+', 'strength': '4', 'toughness': '4', 'wounds': '5', 'attacks': '4', 'leadership': '9', 'save': '3+'}}}
    
    data = [{'unit': key, **values[key]} for key, values in d.items()]
    nycphil = pd.DataFrame(data)
    

    【讨论】:

    • 当我这样做时,我收到一条我以前从未见过的错误消息。我对列表理解不太熟悉 import json #load json object with open('./archive/chaos-space-marines.json') as f: d = json.load(f) data = [ {'unit': key, **values[key]} for key, values in d.items()] nycphil = pd.DataFrame(data)
    • TypeError: 'str' 对象不是映射
    • 我尝试了几种不同的方法,例如循环遍历内部字典与上述方式类似,但我得到类似的错误AttributeError: 'str' object has no attribute 'items'
    • 我将尝试使用这个确切的子集,看看会发生什么。也许列表中有错误
    • 所以它适用于我在此处发布的这个子集,但不适用于原版。我需要调查
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-08-02
    • 2014-04-15
    • 2020-07-21
    • 1970-01-01
    • 2020-12-14
    相关资源
    最近更新 更多