如何为Pandas DataFrame中重复日期时间行添加秒数区分?
Pandas处理重复时间戳:给重复行递增添加秒数
现有如下Pandas DataFrame:
Date time LifeTime1 LifeTime2 LifeTime3 LifeTime4 LifeTime5 2020-02-11 17:30:00 6 7 NaN NaN 3 2020-02-11 17:30:00 NaN NaN 3 3 NaN 2020-02-12 15:30:00 2 2 NaN NaN 3 2020-02-16 14:30:00 4 NaN NaN NaN 1 2020-02-16 14:30:00 NaN 7 NaN NaN NaN 2020-02-16 14:30:00 NaN NaN 8 2 NaN
需求:若为唯一日期时间则保持不变;若有2条重复行,首行不变,第二行添加1秒;若有3条重复行,首行不变,第二行加1秒、第三行加2秒。请问能否在Pandas中便捷实现该操作?
当然可以,用Pandas的分组和时间偏移功能就能快速实现,步骤如下:
1. 转换时间列为datetime类型
首先确保Date time列是datetime格式,这样才能进行时间运算:
import pandas as pd # 构造示例DataFrame(已有数据可跳过此步) df = pd.DataFrame({ 'Date time': ['2020-02-11 17:30:00', '2020-02-11 17:30:00', '2020-02-12 15:30:00', '2020-02-16 14:30:00', '2020-02-16 14:30:00', '2020-02-16 14:30:00'], 'LifeTime1': [6, pd.NA, 2, 4, pd.NA, pd.NA], 'LifeTime2': [7, pd.NA, 2, pd.NA, 7, pd.NA], 'LifeTime3': [pd.NA, 3, pd.NA, pd.NA, pd.NA, 8], 'LifeTime4': [pd.NA, 3, pd.NA, pd.NA, pd.NA, 2], 'LifeTime5': [3, pd.NA, 3, 1, pd.NA, pd.NA] }) # 转为datetime类型 df['Date time'] = pd.to_datetime(df['Date time'])
2. 分组生成递增秒数偏移
按Date time分组,用cumcount()获取每组内的行序号(从0开始),再将序号转为对应秒数的时间偏移量,加到原时间戳上:
# 给重复时间戳添加递增秒数 df['Date time'] = df['Date time'] + pd.to_timedelta(df.groupby('Date time').cumcount(), unit='s')
处理效果
- 原重复两次的
2020-02-11 17:30:00会变为2020-02-11 17:30:00和2020-02-11 17:30:01 - 原重复三次的
2020-02-16 14:30:00会变为2020-02-16 14:30:00、2020-02-16 14:30:01、2020-02-16 14:30:02 - 唯一的时间戳保持原样不变
内容的提问来源于stack exchange,提问作者zape
相关产品推荐
相关产品推荐

