本文介绍了一个月的一周 pandas 的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想每个月有一个星期,有些月份可能有四个星期,有些月份可能有五个星期.对于每个日期,我想知道它属于哪个星期.我最感兴趣的是该月的最后一周.

I'm trying to get week on a month, some months might have four weeks some might have five.For each date i would like to know to which week does it belongs to. I'm mostly interested in the last week of the month.

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

推荐答案

请参阅此,然后确定您要在每月的哪一周.

See this answer and decide which week of month you want.

没有内置的内容,因此您需要使用apply进行计算.例如,对于一个简单的已经过去了多少个7天"度量.

There's nothing built-in, so you'll need to calculate it with apply. For example, for an easy 'how many 7 day periods have passed' measure.

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

要更复杂(基于日历),请使用该答案中的功能.

For a more complicated (based on the calender), using the function from that answer.

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)

这篇关于一个月的一周 pandas 的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-24 01:10