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

Python处理DataFrame重复行:保留首行并覆盖end列值

处理DataFrame重复uniqueId:保留首行并替换end为最后一行的end值

原始数据

indexerrorIdstartendtimestampuniqueId
014042022-04-25 02:10:412022-04-25 02:10:462022-04-251404_2022-04-25
113022022-04-25 02:10:412022-04-25 02:10:462022-04-251302_2022-04-25
214042022-04-27 12:54:462022-04-27 12:54:512022-04-251404_2022-04-25
313022022-04-27 13:34:432022-04-27 13:34:502022-04-251302_2022-04-25
414042022-04-29 04:30:222022-04-29 04:30:292022-04-251404_2022-04-25
513022022-04-29 08:26:252022-04-29 08:26:322022-04-251302_2022-04-25

需求

uniqueId由errorId与timestamp组合生成,需处理该列重复值:

  • 对重复的uniqueId,保留首次出现的行
  • 将首行的end值替换为该uniqueId最后一次出现行的end值

解决方案

使用Pandas的groupby结合聚合函数实现,代码如下:

import pandas as pd

# 构造原始DataFrame
data = {
    'index': [0,1,2,3,4,5],
    'errorId': [1404,1302,1404,1302,1404,1302],
    'start': ['2022-04-25 02:10:41','2022-04-25 02:10:41','2022-04-27 12:54:46','2022-04-27 13:34:43','2022-04-29 04:30:22','2022-04-29 08:26:25'],
    'end': ['2022-04-25 02:10:46','2022-04-25 02:10:46','2022-04-27 12:54:51','2022-04-27 13:34:50','2022-04-29 04:30:29','2022-04-29 08:26:32'],
    'timestamp': ['2022-04-25']*6,
    'uniqueId': ['1404_2022-04-25','1302_2022-04-25','1404_2022-04-25','1302_2022-04-25','1404_2022-04-25','1302_2022-04-25']
}
df = pd.DataFrame(data).set_index('index')

# 分组聚合:保留首行的start/errorId/timestamp,取最后一行的end
grouped = df.groupby('uniqueId').agg({
    'errorId': 'first',
    'start': 'first',
    'end': 'last',
    'timestamp': 'first'
}).reset_index()

# 还原原始首行的index
grouped['index'] = df.groupby('uniqueId').apply(lambda x: x.index[0]).values

# 调整列顺序与原始一致
result = grouped.reindex(columns=['index', 'errorId', 'start', 'end', 'timestamp', 'uniqueId'])

最终结果

indexerrorIdstartendtimestampuniqueId
014042022-04-25 02:10:412022-04-29 04:30:292022-04-251404_2022-04-25
113022022-04-25 02:10:412022-04-29 08:26:322022-04-251302_2022-04-25

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.05 08:10:24