【问题标题】:How to drop duplicates while keeping records based on time difference condition?如何在根据时差条件保留记录的同时删除重复项?
【发布时间】:2021-09-12 20:12:13
【问题描述】:

我有以下熊猫数据框df

Datetime              NewDatetime            Value
2020-03-24 09:00      2020-03-24 12:00       10 
2020-03-24 09:00      2020-03-24 13:00       11
2020-03-24 09:00      2020-03-24 14:00       10
2020-03-24 09:00      2020-03-24 15:00       12
2020-03-24 10:00      2020-03-24 12:00       10 
2020-03-24 10:00      2020-03-24 13:00       11
2020-03-24 10:00      2020-03-24 14:00       11
2020-03-24 10:00      2020-03-24 15:00       12
2020-03-24 11:00      2020-03-24 12:00       10 
2020-03-24 11:00      2020-03-24 13:00       16
2020-03-24 11:00      2020-03-24 14:00       11
2020-03-24 11:00      2020-03-24 15:00       12
2020-03-24 12:00      2020-03-24 12:00       12 
2020-03-24 12:00      2020-03-24 13:00       13
2020-03-24 12:00      2020-03-24 14:00       11
2020-03-24 12:00      2020-03-24 15:00       15

我需要删除NewDatetime 的重复记录,并将NewDatetimeDatetime 之间的差异记录保留为3 小时。

这是预期的结果:

Datetime              NewDatetime            Value
2020-03-24 09:00      2020-03-24 12:00       10  
2020-03-24 10:00      2020-03-24 13:00       11
2020-03-24 11:00      2020-03-24 14:00       11
2020-03-24 12:00      2020-03-24 15:00       15

我该怎么做?

我知道如何删除重复并保留最后的记录,但不确定如何添加时差条件:

df.drop_duplicates(["NewDatetime"], keep='last')

【问题讨论】:

  • 你卡在哪里了?你给出了一对定义明确的操作。依次应用:去掉相差不到三个小时的,然后drop_duplicates。

标签: python pandas


【解决方案1】:

试试:

df['Datetime']=pd.to_datetime(df['Datetime'])
df['NewDatetime']=pd.to_datetime(df['NewDatetime'])
#ensure that both columns are of datetime dtype

然后:

m=((df['NewDatetime']-df['Datetime']).dt.total_seconds()/3600).eq(3)
#check your condition If the difference between these 2 is equal to 3 hrs or not

最后:

df[m]
#OR
df.loc[m]
#passed the condition

【讨论】:

  • 为什么不只是seconds 而不是total_seconds()
  • @not_speshal 如果您在+1 days 03:00:00 中有时间增量,则表示 27 小时,但是当您使用 .dt.seconds 时,它会给您 10800 秒,但如果您使用 .dt.total_seconds(),它会给您 @ 987654330@秒
【解决方案2】:

你可以使用 TimeDelta 对象来比较我的想法。

In [32]: (pd.to_datetime('2020-03-24 12:00') - pd.to_datetime('2020-03-24 09:00')) == pd.Timedelta('3 hours')
Out[32]: True

In [33]: (pd.to_datetime('2020-03-24 12:00') - pd.to_datetime('2020-03-24 09:12')) == pd.Timedelta('3 hours')
Out[33]: False

【讨论】:

    猜你喜欢
    • 2020-10-07
    • 1970-01-01
    • 1970-01-01
    • 2022-01-17
    • 2021-08-27
    • 1970-01-01
    • 2019-04-04
    • 2019-12-20
    • 2023-01-12
    相关资源
    最近更新 更多