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

Python如何按License、Location、Date分组对重复行的Quantity求和

解法

你需要补充日期格式转换、分组聚合的逻辑,完整代码如下:

import pandas as pd

def migrate(df, template):
    inventory = df.copy()
    # 保留除Type外的所有字段,无需手动筛选全量字段
    inventory = inventory.drop(columns=['Type'])
    # 转换日期列为datetime格式,确保可正确提取月份维度
    inventory['Date'] = pd.to_datetime(inventory['Date'], errors='coerce')
    # 生成临时月份列作为分组依据
    inventory['month'] = inventory['Date'].dt.to_period('M')
    # 按License、Location、同月份维度分组,Quantity求和,其余同组字段取首值
    inventory = inventory.groupby(['License', 'Location', 'month'], as_index=False).agg(
        Date=('Date', 'first'),
        Quantity=('Quantity', 'sum'),
        # 如有其他需保留的字段,按 字段名=('字段名', '聚合函数') 格式补充即可
    ).drop(columns=['month'])
    # 若需要日期统一显示为当月第一天,可启用下面这行代码
    # inventory['Date'] = inventory['Date'].dt.to_period('M').dt.to_timestamp()
    return inventory

关键逻辑说明

  • 用drop删除指定列比手动选全量需保留字段效率更高,也不会出现漏字段的问题
  • pd.to_datetime中加了errors='coerce'参数,会把非法日期转为空值,避免转换报错中断迁移流程
  • 临时增加的month列确保聚合是在同一个月内执行,不会把不同月份的同License、Location数据合并
  • 若同组内除Quantity外的其他字段存在不同取值,可根据业务需求调整聚合函数,替换为max、min或自定义规则即可

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.07 06:54:05