熊猫识别当前日期,并相对于当前日期过滤日期列



在pandas/python中翻译下面的逻辑时遇到很多麻烦,所以我甚至没有示例代码或df可以使用:x

我运行一个每日报告,基本上过滤从星期一到"今天"前一天的数据。我有一个日期列[采用dt.strftime('%#m/%#d/%Y')格式]。它永远不会超过周一至周日的范围。

1)在运行报告时识别"今天"的日期,并识别星期一前的壁橱是哪一天。过滤今天日期前一天的星期一的"日期"列 [ dt.strftime('%#m/%#d/%Y') 格式]

2)过滤df后,在上面的逻辑中获取这组具有日期的行,让它在新列"Date2"中检查日期。如果任何日期早于星期一日期,则在 Date2 中,将"Date2"中的所有较早日期更改为"日期"列中的星期一日期。

3)如果"今天"是星期一,则在"日期"列中过滤从上一个星期一到星期日的范围。在过滤后,请执行上述步骤[步骤 2],但对于"Date2"列中属于星期六和星期日日期的任何日期,请将其更改为星期五日期。

这有意义吗?

步骤如下:

from datetime import datetime
today = pd.to_datetime(datetime.now().date())
day_of_week = today.dayofweek
last_monday = today - pd.to_timedelta(day_of_week, unit='d') 
# if today is Monday, we need to step back another week
if day_of_week == 0:
last_monday -= pd.to_timedelta(7, unit='d')
# filter for last Monday
last_monday_flags = (df.Date == last_mon)
# filter for Date2 < last Monday
date2_flags = (df.Date2 < last_monday)
# update where both flags are true
flags = last_monday_flags & date2_flags
df.loc[flags, 'Date2'] = last_monday
# if today is Monday
if day_of_week == 0: 
last_sunday = last_monday + pd.to_timedelta(6, unit='d')
last_sat = last_sunday - pd.to_timedelta(1, unit='d')
last_week_flags = (df.Date >= last_monday) & (df.Date <= next_sunday)
last_sat_flags = (df.Date2 == last_sat)
last_sun_flags = (df.Date2 == last_sun)
# I'm just too lazy and not sure how Sat and Sun relates to Fri
# but i guess just subtract 1 day or 2 depending on which day
...

最新更新