相关疑难解决方法(0)

展平嵌套的Python词典,压缩键

假设你有一个字典,如:

{'a': 1,
 'c': {'a': 2,
       'b': {'x': 5,
             'y' : 10}},
 'd': [1, 2, 3]}
Run Code Online (Sandbox Code Playgroud)

你会如何将其扁平化为:

{'a': 1,
 'c_a': 2,
 'c_b_x': 5,
 'c_b_y': 10,
 'd': [1, 2, 3]}
Run Code Online (Sandbox Code Playgroud)

python dictionary

147
推荐指数
13
解决办法
10万
查看次数

在熊猫数据框中展平嵌套的 Json

我正在尝试将 json 文件加载到 Pandas 数据框。我发现有一些嵌套的json。下面是示例 json:

{'events': [{'id': 142896214,
   'playerId': 37831,
   'teamId': 3157,
   'matchId': 2214569,
   'matchPeriod': '1H',
   'eventSec': 0.8935539999999946,
   'eventId': 8,
   'eventName': 'Pass',
   'subEventId': 85,
   'subEventName': 'Simple pass',
   'positions': [{'x': 51, 'y': 49}, {'x': 40, 'y': 53}],
   'tags': [{'id': 1801, 'tag': {'label': 'accurate'}}]}
Run Code Online (Sandbox Code Playgroud)

我使用以下代码将 json 加载到数据帧中:

with open('EVENTS.json') as f:
    jsonstr = json.load(f)

df = pd.io.json.json_normalize(jsonstr['events'])
Run Code Online (Sandbox Code Playgroud)

下面是 df.head() 的输出

df 的输出

这是输出

但是我发现了两个嵌套的列,例如位置和标签。

我尝试使用以下代码将其展平:

Position_data = json_normalize(data =jsonstr['events'], record_path='positions', meta = ['x','y','x','y'] )
Run Code Online (Sandbox Code Playgroud)

它向我显示了如下错误:

KeyError: "Try running with errors='ignore' as key 'x' is …
Run Code Online (Sandbox Code Playgroud)

python json flatten pandas json-normalize

14
推荐指数
2
解决办法
2万
查看次数

标签 统计

python ×2

dictionary ×1

flatten ×1

json ×1

json-normalize ×1

pandas ×1