比较两个日期的条件

2024-05-03 04:15:57 发布

您现在位置:Python中文网/ 问答频道 /正文

如果date_>buy_date大于12个月,其他0

示例df

customer_id   date_         buy_date
34555        2019-01-01    2017-02-01
24252        2019-01-01    2018-02-10
96477        2019-01-01    2017-02-18

输出测向

customer_id   date_         buy_date    buy_date>_than_12_months
34555        2019-01-01    2017-02-01    1
24252        2019-01-01    2018-02-10    0
96477        2019-01-01    2018-02-18    1

2条回答
import pandas as pd
import numpy as np

values = {'customer_id': [34555,24252,96477],
          'date_':  ['2019-01-01','2019-01-01','2019-01-01'],
          'buy_date':  ['2017-02-01','2018-02-10','2017-02-18'],
          }

df = pd.DataFrame(values, columns = ['customer_id', 'date_', 'buy_date'])

df['date_'] = pd.to_datetime(df['date_'], format='%Y-%m-%d')
df['buy_date'] = pd.to_datetime(df['buy_date'], format='%Y-%m-%d')

print(df['date_'] - df['buy_date'])

df['buy_date>_than_12_months'] = pd.Series([1 if ((df['date_'] - df['buy_date'])[i]> np.timedelta64(1, 'Y')) else 0 for i in range(3)])
print (df)

根据我的理解,您可以尝试在buy_date上加上一年,然后从date_中减去,然后检查天数是+还是-

 df['buy_date>_than_12_months'] = ((df['date_'] - 
                               (df['buy_date']+pd.offsets.DateOffset(years=1)))
                                  .dt.days.gt(0).astype(int))

print(df)

   customer_id      date_   buy_date  buy_date>_than_12_months
0        34555 2019-01-01 2017-02-01                         1
1        24252 2019-01-01 2018-02-10                         0
2        96477 2019-01-01 2017-02-18                         1

相关问题 更多 >