pandas 日期计算(格式转换、单位相关)

背景

因工作需要,从hive数仓里面下载了一份数据,需要计算在优惠券生命周期内用券的用户树。
数据样式如下:

df_coupon = pd.read_excel(r'../coupon.xlsx')
df_coupon.head()
 a.user_id  a.credit_userid a.partition_date b.coupon_obtain_date
0   16865549         16865549       2019-06-30           2019-06-30
1   16865549         16865549       2019-06-30           2019-06-30
2   23311751         23311751       2019-07-03           2019-07-03
3   24491906         24491906       2019-07-06           2019-07-06
4   24491906         24491906       2019-07-06           2019-07-06

解决思路

1)以str格式储存的两列无法直接相减:

df_coupon['a.partition_date'] - df_coupon['b.coupon_obtain_date']
TypeError: unsupported operand type(s) for -: 'str' and 'str'

所以要把这两列转化为日期格式,这里有多种方法,我用的是pandas自带的to_datetime方法

df_coupon['a.partition_date'] = pd.to_datetime(df_coupon['a.partition_date']) 
df_coupon['b.coupon_obtain_date'] = pd.to_datetime(df_coupon['b.coupon_obtain_date'])

2)转化为日期之后的两列可以直接相减,得到相差的天数,但是天数不能直接与数值作比较:

df[df_coupon['a.partition_date']-df_coupon['b.coupon_obtain_date']<=1]
TypeError: Invalid comparison between dtype=timedelta64[ns] and int

所以这里要把天数转化为数值,再进行比较,我用的是dt.days方法。注意:对DataFrame进行切片的时候,如果有多个条件,只能用&而不能用 and,并且不同条件要用括号括起来

df_coupon['date_diff'] = df_coupon['a.partition_date']-df_coupon['b.coupon_obtain_date']
df_coupon['date_diff'] = df_coupon['date_diff'].dt.days
df_coupon[(df_coupon['date_diff'] <=1) & (df_coupon['date_diff' ] >=0)].shape[0]

得到用户数

Out[20]: 7675

你可能感兴趣的:(pandas,日期计算)