Calculate Last Friday of Month in Pandas

前端 未结 3 1489
野性不改
野性不改 2021-01-15 06:34

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 = cale         


        
3条回答
  •  粉色の甜心
    2021-01-15 06:51

    Scalar datetime objects don't have a dt accessor, series do: see pd.Series.dt. If you remove this, your function works fine. The key is understanding that pd.Series.apply passes scalars to your custom function via a loop, not an entire series.

    def last_thurs_date(date):
        month = date.month
        year = date.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
    

    You can rewrite your logic more succinctly via f-strings (Python 3.6+) and a ternary statement:

    def last_thurs_date(date):
        month = date.month
        year = date.year
        last_thurs_date = calendar.monthcalendar(year, month)[4][4]
        return f'{year}{"-0" if month < 10 else "-"}{month}-{last_thurs_date}'
    

提交回复
热议问题