python - 使用通用条目合并 json 数组
问题描述
我有一个 python 脚本,它使用 Get API 给我两个 json 数组
数据1
{'result': [
{'number': '0010041', 'month': 'January'},
{'number': '0010042', 'month': 'March'}
]}
数据2
{'result': [
{'task': '0010041', 'time_left': '20 sec'},
{'task': '0010042', 'time_left': '6 min'}
]}
我想使用公共条目合并两者,因此在这种情况下,它们相同的“数字”和“任务”合并数组中的其余数据。
例如。
'number': '0010041', 'month': 'January', 'time_left': '20 sec'
'number': '0010042', 'month': 'March', 'time_left': '6 min'
如何?
解决方案
这是使用pandas
库的一种方式:
import pandas as pd
from pandas.io.json import json_normalize
d1 = json_normalize(d1['result'])
d2 = json_normalize(d2['result'])
# merge the data
lst = d1.merge(d2, left_on='number', right_on='task').drop('task', axis=1)
# converting time to same units (seconds)
lst['time_secs'] = lst['time_left'].str.split().apply(lambda x: int(x[0])*60 if 'min' in x else int(x[0]))
# sort, select cols and convert to dictionary
lst = lst.sort_values('time_secs', ascending=True)[['number','month','time_left']].to_dict(orient='records')
[{'number': '0010041', 'month': 'January', 'time_left': '20 sec'},
{'number': '0010042', 'month': 'March', 'time_left': '6 min'}]
推荐阅读
- javascript - 三个 JS - 使对象在悬停时远离鼠标倾斜?
- npm - 错误:EACCES:权限被拒绝,打开“/root/.config/truffle/config.json”
- ios - 获取孩子的参数与获取没有参数的孩子有何不同?
- assembly - 为什么push先减少堆栈指针?
- python - pytest 标记:标记整个目录/包
- openlayers - 是否有任何自动方法可以在 openlayers 中发现 epsg 代码和 proj4 到 geojson 文件?
- javascript - 如何在 Storybook 上实时编辑类/功能组件
- javascript - 用我的 HTML 编写的图像不可见
- ruby-on-rails - ActiveRecord::QueryMethods 中#references 方法的参数有什么意义?
- vue.js - 是否可以动态替换 graphql/apollo 查询中的字段以及变量?