【发布时间】:2021-05-25 20:39:56
【问题描述】:
我昨天问了一个关于如何将 JSON 文件转换为数据框的问题,但我问错了问题
我有一个如下所示的 JSON 文件
有两个级别的键(有时重复,有时不重复)
{
"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 Space Marines": {
"Chaos Space Marine": {
"model_count": "4-19",
"points_value": "14",
"movement": "6\"",
"weapon_skill": "3+",
"ballistic_skill": "3+",
"strength": "4",
"toughness": "4",
"wounds": "1",
"attacks": "1",
"leadership": "7",
"save": "3+"
},
"Aspiring Champion": {
"model_count": "1",
"points_value": "14",
"movement": "6\"",
"weapon_skill": "3+",
"ballistic_skill": "3+",
"strength": "4",
"toughness": "4",
"wounds": "1",
"attacks": "2",
"leadership": "8",
"save": "3+"
}
}
}
我想将其转换为如下所示的数据框:
| unit | model | model_count | points_value | movement | weapon_skill | ballistic_skill | strength | toughness | wounds | attacks | leadership | save |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
| Abaddon the Despoiler | Abaddon the Despoiler | 1 | 220\u2022 | 6" | 2+ | 2+ | 5 | 5 | 8 | 6 | 10 | +2 |
| Chaos Space Marines | Chaos Space Marines | 4-19 | 14 | 6" | 3+ | 3+ | 4 | 4 | 1 | 1 | 7 | +3 |
| Chaos Space Marines | Aspiring Champion | 1 | 14 | 6" | 3+ | 3+ | 4 | 4 | 1 | 2 | 8 | +3 |
@azro 昨天为我的问题提供了这个有用的答案,但我问错了问题。在最初的问题中,我想跳过第二级键,所以它看起来像下面
| 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 |
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)
【问题讨论】: