python - 按子json的元素聚合json
问题描述
我有以下结构:
[
{
"Name": "a-1",
"Tags": [
{
"Value": "a",
"Key": "Type"
}
],
"CreationDate": "2018-02-25T17:33:19.000Z"
},
{
"Name": "a-2",
"Tags": [
{
"Value": "a",
"Key": "Type"
}
],
"CreationDate": "2018-02-26T17:33:19.000Z"
},
{
"Name": "b-1",
"Tags": [
{
"Value": "b",
"Key": "Type"
}
],
"CreationDate": "2018-01-21T17:33:19.000Z"
},
{
"Name": "b-2",
"Tags": [
{
"Value": "b",
"Key": "Type"
}
],
"CreationDate": "2018-01-22T17:33:19.000Z"
},
{
"Name": "c-1",
"Tags": [
{
"Value": "c",
"Key": "Type"
}
],
"CreationDate": "2018-08-29T17:33:19.000Z"
}
]
当组中有多个成员时,我想打印出Name
每个成员中最旧的(这应该是可配置的。例如:当成员超过 y 时,x 最旧的项目)。Value
在这种情况下,有两个a
,两个b
和一个c
,所以预期的结果将是:
a-1
b-1
如果我的 Python 代码在这里:
data = ec2.describe_images(Owners=['11111'])
images = data['Images']
grouper = groupby(map(itemgetter('Tags'), images))
groups = (list(vals) for _, vals in grouper)
res = list(chain.from_iterable(filter(None, groups)))
当前res
仅包含 and 的列表,Key
并且Value
未分组。任何人都可以向我展示如何将代码继续到预期的结果?
解决方案
这是一个使用 pandas 的解决方案,它需要一个 json 字符串作为输入 ( json_string
)
很多时候 pandas 是矫枉过正的,但在这里我认为它会很好,因为你基本上想按价值分组,然后根据他们有多少成员等标准消除一些组
import pandas as pd
# load the dataframe from the json string
df = pd.read_json(json_string)
df['CreationDate'] = pd.to_datetime(df['CreationDate'])
# create a value column from the nested tags column
df['Value'] = df['Tags'].apply(lambda x: x[0]['Value'])
# groupby value and iterate through groups
groups = df.groupby('Value')
output = []
for name, group in groups:
# skip groups with fewer than 2 members
if group.shape[0] < 2:
continue
# sort rows by creation date
group = group.sort_values('CreationDate')
# save the row with the most recent date
most_recent_from_group = group.iloc[0]
output.append(most_recent_from_group['Name'])
print(output)
推荐阅读
- node.js - 根据服务器上的 X 时间将用户移动到不同的角色
- grafana - 如何制作只有颜色和文本作为链接的 Grafana 面板?
- node.js - CircleCI 中的 package-lock.json 有什么问题?
- html - display:table-row 在除 FireFox 之外的浏览器中不起作用
- php - 如何在 Laravel 中使用左连接查找匹配记录
- here-api - 我可以请求具有最大坡度或海拔变化的卡车路线吗?
- python - 循环遍历包含字符串的列表
- angular - 如何从 TypeScript 文件中的父级获取子组件变量和函数
- python - 如何在用户输入结束时搜索特定字符?
- html - 图像在 html/css 中过于拉伸