gpt4 book ai didi

python - pandas如何计算仅给定月份和日期的增量

转载 作者:行者123 更新时间:2023-12-01 00:50:05 24 4
gpt4 key购买 nike

我有以下df

doc_date    date_string
2019-06-03 WW0306
2019-06-07 EH0706

doc_datedatetime64,格式为 year-month-daydate_string 是字符串 dtype,如果删除非数字字符,则具有 day/monthmonth/day 格式;

df['date_string'].str.replace(r'\D+', '')

如何将 date_string 转换为 datetime64,并在 date_string 的情况下将标记 within_180 设置为 true 位于 doc_date 的 +/- 180 天内,不考虑它没有年份和转换成的任何日期格式;

 df['within_180'] = df.apply(lambda x: x.between(x.doc_date -
Timedelta(180, unit='d'),
x.doc_date +
Timedelta(180, unit='d')))

结果应该是这样的,

doc_date    date_string    within_180
2019-06-03 WW0306 true
2019-06-07 EH0706 true

最佳答案

IIUC,您在 replace 后将 date_string 列转换为日期时间并使用 series.dt.dayofyear访问两列的日期并与 series.le() 进行比较:

s=pd.to_datetime(df['date_string'].str.replace(r'\D+', ''),format='%d%m')
#df.doc_date=pd.to_datetime(df.doc_date) convert to datetime if not already datetime
df['withith_180'] = (df.doc_date.dt.dayofyear-s.dt.dayofyear).le(180)
<小时/>
    doc_date date_string  withith_180
0 2019-06-03 WW0306 True
1 2019-06-07 EH0706 True

关于python - pandas如何计算仅给定月份和日期的增量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56635186/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com