python - 根据 dateTime 创建子组
问题描述
所以我在一个列表中有一个对象列表,其中有 600 多个。
我在这里有一个对象示例:
{'Description': '', 'Encrypted': False, 'OwnerId': '', 'Progress': '100%', 'SnapshotId': '', 'StartTime': datetime.datetime(2021, 7, 16, 22, 47, 50, 383000, tzinfo=tzlocal()) }
问题是我有一个列表/数组,我想将它们全部分组到子组中,以便每个对象与其他对象分组到一个组中,这些对象的时间戳记为“StartTime”日期时间,彼此在 5 分钟内。我已经为此工作了一个多星期,但我不知道如何进行此分组。将它们分组后,我需要对每个组应用一些规则,以确保它们具有正确的标签和信息。
仅供参考,这些是由 amazon aws boto3 describe_snapshots 方法创建的快照对象。你可以在这里阅读它们:https ://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/ec2.html#EC2.Client.describe_snapshots
解决方案
您可以使用pandas
它来对数据框进行分组pd.Grouper(key='StartTime', freq='5min')
:
import pandas as pd
import datetime
from dateutil.tz import tzlocal
data = [{'Description': '', 'Encrypted': False, 'OwnerId': '', 'Progress': '100%', 'SnapshotId': '', 'StartTime': datetime.datetime(2021, 7, 16, 22, 47, 50, 383000, tzinfo=tzlocal()) },{'Description': '', 'Encrypted': False, 'OwnerId': '', 'Progress': '100%', 'SnapshotId': '', 'StartTime': datetime.datetime(2021, 7, 16, 22, 48, 50, 383000, tzinfo=tzlocal()) },{'Description': '', 'Encrypted': False, 'OwnerId': '', 'Progress': '100%', 'SnapshotId': '', 'StartTime': datetime.datetime(2021, 7, 16, 22, 58, 50, 383000, tzinfo=tzlocal()) },{'Description': '', 'Encrypted': False, 'OwnerId': '', 'Progress': '100%', 'SnapshotId': '', 'StartTime': datetime.datetime(2021, 7, 16, 22, 59, 50, 383000, tzinfo=tzlocal()) }]
df = pd.DataFrame(data)
df_grouped = df.groupby(pd.Grouper(key='StartTime', freq='5min'))
或者,您可以在原始数据框中创建一个带有组号的额外行。例如:
def bin_number(table):
table['bin'] = list(df_grouped.groups.keys()).index(table.name)
return table
df_grouped = df.groupby(pd.Grouper(key='StartTime', freq='5min'), as_index=False)
df_grouped = df_grouped.apply(bin_number).reset_index()
输出:
指数 | 描述 | 加密 | 所有者 ID | 进步 | 快照 ID | 开始时间 | 垃圾桶 | |
---|---|---|---|---|---|---|---|---|
0 | 0 | 错误的 | 100% | 2021-07-16 22:47:50.383000+02:00 | 0 | |||
1 | 1 | 错误的 | 100% | 2021-07-16 22:48:50.383000+02:00 | 0 | |||
2 | 2 | 错误的 | 100% | 2021-07-16 22:58:50.383000+02:00 | 2 | |||
3 | 3 | 错误的 | 100% | 2021-07-16 22:59:50.383000+02:00 | 2 |
推荐阅读
- selenium - 如何跳过基于 Selenium OS 运行测试的 TestNG 测试
- javascript - mochawesome 报告的名称未按预期保存(即使 cypress.json 中的“reportFilename”已更改)
- database - 同一 Oracle 11 行上的两个并发更新会导致死锁或更新失败吗?
- python - 仅当有 24 个连续 NAN 或更多时才填充 NAN 值
- python - 如果 x 列字符串在 y 列字符串中,则加入数据框
- time - 在 Google 表格中计算超过 24 小时的时间
- docker - Traefik 2.0:有条件地添加标头(用于 Grafana 的身份验证)
- python - 在数学计算中尝试所有可能的括号放置
- powershell - powershell计划任务中的功能不起作用
- android - 用于在 Android 中保存文件的 GlobalScope