如何在多逻辑语句中比较数据框之间的日期时间?

时间:2019-02-20 01:10:25

标签: python-3.x pandas datetime dataframe

在从多逻辑语句内部比较两个数据框之间的日期时遇到问题。

df1:

 EmailAddress     DateTimeCreated
    1@1        2019-02-12 20:47:00

df2:

 EmailAddress     DateTimeCreated
  1@1.com         2019-02-07 20:47:00
  2@2.com         2018-11-13 20:47:00
  3@3.com         2018-11-04 20:47:00

只要df1中有一行,我就想做三件事:

 1. Compare to see if `EmailAddress` from df1 is present in df2:
 1a. If `EmailAddress` is present, compare `DateTimeCreated` in df1 to `DateTimeCreated` in df2, 
 2. If `DateTimeCreated` in df1 is greater than today-90 days append df1 into df2. 

用简单的话来说:

我想查看df2中是否存在电子邮件地址,如果存在,请比较在df2中创建的日期时间,以查看该地址是否大于上次有人回答以来的今天-90天。如果已超过90天,则将df1中的行追加到df2中。

我的逻辑是将所有内容附加到不确定我在做什么的地方,像这样:

import pandas as pd
from datetime import datetime, timedelta

df2.append(df2.loc[df2.EmailAddress.isin(df1.EmailAddress)&(df2.DateTimeCreated.ge(datetime.today() - timedelta(90)))])

我搞错了约会怎么办?

编辑:

在上面的示例中,在数据框之间,不会将df1中的行附加起来,因为DateTimeCreated位于TODAY()-90天之间。

2 个答案:

答案 0 :(得分:2)

请参考内联注释以获取解释。请注意,在此解决方案中,您需要重命名df1列以匹配df2列。

import pandas as pd
import datetime

from datetime import timedelta, datetime

df1 = pd.DataFrame({'EmailAddress':['2@2.com'], 'DateTimeCreated':[datetime(2019,2,12,20,47,0)]})
df2 = pd.DataFrame({'EmailAddress':['1@1.com', '2@2.com', '3@3.com'], 
    'DateTimeCreated':[
        datetime(2019,2,7,20,47,0), 
        datetime(2018,11,13,20,47,0), 
        datetime(2019,11,4,20,47,0)]})

# Get all expired rows
df3 = df2.loc[datetime.now() - df2['DateTimeCreated'] > timedelta(days=90)]
# Update it with the timestamp from df1
df3 = df3.set_index('EmailAddress').join(df1.set_index('EmailAddress'), how='inner', rsuffix='_r')
df3.drop('DateTimeCreated', axis=1, inplace=True)
df3.columns = ['DateTimeCreated']
# Patch df2 with the latest timestamp
df2 = df3.combine_first(df2.set_index('EmailAddress')).reset_index()

# Patch again for rows in df1 that are not in df2
df1 = df1.loc[df1['EmailAddress'].apply(lambda x: 1 if x not in df2['EmailAddress'].tolist() else 0) == 1]
df2 = pd.concat([df2, df1])

>>>df2
  EmailAddress     DateTimeCreated
0      1@1.com 2019-02-07 20:47:00
1      2@2.com 2019-02-12 20:47:00
2      3@3.com 2019-11-04 20:47:00

答案 1 :(得分:0)

尝试 1.满足条件1电子邮件地址相同的左加入df1和df2     Combined_df = df1.join(df2,how =“ left”,lsuffix =“ df1 _”,rsuffix =“ df2_”) 2.计算df1 datetime创建的日期和今天之间的时间差     差距= pd.datetime.today()-Combined_df.DateTimeCreated_df1

  1. 返回差距大于90的指数 遮罩= Combined_df.gap> 90
  2. df2.append(df1 [mask])

注意:我认为您可能只需要Combined_df,第4步附加操作将导致数据重复或混乱。无论如何,您可以选择使用步骤1,2,3,4或仅使用步骤1,2,3