gpt4 book ai didi

python - 一个月的一周 Pandas

转载 作者:太空狗 更新时间:2023-10-30 01:54:25 25 4
gpt4 key购买 nike

我试图在一个月中得到一周,有些月份可能有四个星期,有些可能有五个星期。对于每个日期,我想知道它属于哪一周。我最感兴趣的是本月的最后一周。

data = pd.DataFrame(pd.date_range(' 1/ 1/ 2000', periods = 100, freq ='D'))

0 2000-01-01
1 2000-01-02
2 2000-01-03
3 2000-01-04
4 2000-01-05
5 2000-01-06
6 2000-01-07

最佳答案

查看此 answer并决定您想要在一个月中的哪一周。

没有内置的东西,所以你需要用 apply 来计算它。例如,对于一个简单的“已经过去了多少 7 天”的度量。

data['wom'] = data[0].apply(lambda d: (d.day-1) // 7 + 1)

对于更复杂的(基于日历),使用该答案中的函数。

import datetime
import calendar

def week_of_month(tgtdate):
tgtdate = tgtdate.to_datetime()

days_this_month = calendar.mdays[tgtdate.month]
for i in range(1, days_this_month):
d = datetime.datetime(tgtdate.year, tgtdate.month, i)
if d.day - d.weekday() > 0:
startdate = d
break
# now we canuse the modulo 7 appraoch
return (tgtdate - startdate).days //7 + 1

data['calendar_wom'] = data[0].apply(week_of_month)

关于python - 一个月的一周 Pandas ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25249033/

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