Python处理DataFrame重复行:保留首行并覆盖end列值
处理DataFrame重复uniqueId:保留首行并替换end为最后一行的end值
原始数据
| index | errorId | start | end | timestamp | uniqueId |
|---|---|---|---|---|---|
| 0 | 1404 | 2022-04-25 02:10:41 | 2022-04-25 02:10:46 | 2022-04-25 | 1404_2022-04-25 |
| 1 | 1302 | 2022-04-25 02:10:41 | 2022-04-25 02:10:46 | 2022-04-25 | 1302_2022-04-25 |
| 2 | 1404 | 2022-04-27 12:54:46 | 2022-04-27 12:54:51 | 2022-04-25 | 1404_2022-04-25 |
| 3 | 1302 | 2022-04-27 13:34:43 | 2022-04-27 13:34:50 | 2022-04-25 | 1302_2022-04-25 |
| 4 | 1404 | 2022-04-29 04:30:22 | 2022-04-29 04:30:29 | 2022-04-25 | 1404_2022-04-25 |
| 5 | 1302 | 2022-04-29 08:26:25 | 2022-04-29 08:26:32 | 2022-04-25 | 1302_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'])
最终结果
| index | errorId | start | end | timestamp | uniqueId |
|---|---|---|---|---|---|
| 0 | 1404 | 2022-04-25 02:10:41 | 2022-04-29 04:30:29 | 2022-04-25 | 1404_2022-04-25 |
| 1 | 1302 | 2022-04-25 02:10:41 | 2022-04-29 08:26:32 | 2022-04-25 | 1302_2022-04-25 |
内容的提问来源于stack exchange,提问作者ranqnova
相关产品推荐
相关产品推荐

