计算每月的最后一个星期五在 pandas [英] Calculate Last Friday of Month in Pandas

查看:111
本文介绍了计算每月的最后一个星期五在 pandas 的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已编写此函数来获取该月的最后一个星期四

I've written this function to get the last Thursday of the month

def last_thurs_date(date):
    month=date.dt.month
    year=date.dt.year
    
    cal = calendar.monthcalendar(year, month)
    last_thurs_date = cal[4][4]
    if month < 10:
        thurday_date = str(year)+'-0'+ str(month)+'-' + str(last_thurs_date)
    else:
        thurday_date = str(year) + '-' + str(month) + '-' + str(last_thurs_date)
    return thurday_date

但它不起作用

datelist['Date'].map(lambda x: last_thurs_date(x))

日期列表在哪里

datelist = pd.DataFrame(pd.date_range(start = pd.to_datetime('01-01-2014',format='%d-%m-%Y')
                                      , end = pd.to_datetime('06-03-2019',format='%d-%m-%Y'),freq='D').tolist()).rename(columns={0:'Date'})
datelist['Date']=pd.to_datetime(datelist['Date'])


推荐答案

Jpp已添加解决方案,但只是添加了更具可读性的格式化字符串-请参见很棒的网站

Jpp already added the solution, but just to add a slightly more readable formatted string - see this awesome website.

import calendar
def last_thurs_date(date):
    year, month = date.year, date.month
    cal = calendar.monthcalendar(year, month)
    # the last (4th week -> row) thursday (4th day -> column) of the calendar
    # except when 0, then take the 3rd week (February exception)
    last_thurs_date =  cal[4][4] if cal[4][4] > 0 else cal[3][4] 
    return f'{year}-{month:02d}-{last_thurs_date}'

还添加了一些逻辑-例如您获得了 2019-02-0 ,因为二月没有整整4周。

Also added a bit of logic - e.g. you got 2019-02-0 as February doesn't have 4 full weeks.

这篇关于计算每月的最后一个星期五在 pandas 的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆