首页 > 解决方案 > 根据 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

标签: pythonamazon-web-services

解决方案


您可以使用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

推荐阅读