You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何通过Pandas条件分组关联Configuration与Product Available事件?

解决方案:分组统计产品使用量

步骤1:数据预处理

先将原始数据加载为DataFrame,转换时间格式并排序,确保时间逻辑正确:

import pandas as pd

data = {
    'Timestamp': ['25/07/2024  08:58:49', '25/07/2024  08:58:49', '25/07/2024  08:58:51', '25/07/2024  10:17:53', '25/07/2024  10:17:53', '25/07/2024  10:17:53', '25/07/2024  10:18:11', '25/07/2024  10:18:11', '25/07/2024  10:18:11', '25/07/2024  10:18:11', '25/07/2024  10:18:11', '25/07/2024  10:18:12'],
    'Event': ['Configuration', 'Product Available', 'Product Available', 'Product Available', 'Configuration', 'Product Available', 'Product Available', 'Product Available', 'Configuration', 'Configuration', 'Product Available', 'Product Available'],
    'Data': ['A,B', 'A,1', 'B,3', 'B,1', 'B,C', 'C,4', 'C,2','B,1','A,B','B,C','B,3','A,1']
}

df = pd.DataFrame(data)
# 转换时间格式为datetime
df['Timestamp'] = pd.to_datetime(df['Timestamp'], format='%d/%m/%Y  %H:%M:%S')
# 按时间排序,确保事件顺序正确
df = df.sort_values('Timestamp').reset_index(drop=True)

步骤2:拆分两类事件

分别处理Configuration和Product Available事件,解析Data列的内容:

处理Configuration事件

config_df = df[df['Event'] == 'Configuration'].copy()
# 拆分Data列得到产品列表
config_df['Products'] = config_df['Data'].str.split(',')
# 标记当前配置的生效结束时间(下一个配置的时间)
config_df['Next_Timestamp'] = config_df['Timestamp'].shift(-1)
# 最后一个配置的结束时间设为远未来
config_df.loc[config_df.index[-1], 'Next_Timestamp'] = pd.Timestamp.max

处理Product Available事件

product_df = df[df['Event'] == 'Product Available'].copy()
# 拆分Data列得到产品和数量,并转换数量为数值类型
product_df[['Product', 'Quantity']] = product_df['Data'].str.split(',', expand=True)
product_df['Quantity'] = product_df['Quantity'].astype(int)

步骤3:关联产品事件与生效配置

用区间匹配将每个产品事件关联到对应的生效配置(即事件发生时处于哪个配置的时间段内):

# 使用merge_asof实现前向匹配,自动关联最近的前序配置
merged_df = pd.merge_asof(
    product_df.sort_values('Timestamp'),
    config_df.sort_values('Timestamp'),
    on='Timestamp',
    direction='backward'
)
# 过滤掉不在配置生效时间段内的事件(若存在)
merged_df = merged_df[merged_df['Timestamp'] < merged_df['Next_Timestamp']]

步骤4:统计产品使用量

根据需求选择统计维度:

1. 按产品累计总使用量

total_usage = merged_df.groupby('Product')['Quantity'].sum().reset_index()
print(total_usage)

输出结果:

Product  Quantity
0       A         2
1       B         8
2       C         6

2. 按配置+产品统计使用量

若需要查看每个配置对应的产品使用情况:

config_product_usage = merged_df.groupby(['Timestamp_x', 'Products', 'Product'])['Quantity'].sum().reset_index()
config_product_usage.rename(columns={'Timestamp_x': 'Config_Timestamp'}, inplace=True)
print(config_product_usage)

关键说明

  • 用merge_asof替代索引匹配,完美解决同时间戳多事件的匹配问题,自动关联最近的生效配置
  • 配置时间段的划分确保每个产品事件都能对应到正确的配置上下文
  • 统计维度可灵活调整,满足不同场景的查看需求

内容的提问来源于stack exchange,提问作者PaulM

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.19 04:44:54