创建一个包含给定年份中所有周末的数据框

Create a dataframe containing all weekends in a given year

下午好,

我想创建一个函数,给定一年,该函数将 return 一个数据框,其中包含与该年的星期六和星期日相关的时间戳格式的所有日期。也就是说:

def get_saturdays_and_sundays(year):
   df = pd.DataFrame()
   # Generate dataframe
   return df

def main():
   print(get_saturdays_and_sundays(2022))

if __name__ == '__main__':  
    main()

函数会 return:

|      date                 |     day          |
|---------------------------|------------------|
|          2022-01-01       |     Saturday     |
|          2022-01-02       |     Sunday       |
|          2022-01-08       |     Saturday     |
|          2022-01-09       |     Sunday       |
...
|          2022-12-24       |     Saturday     |
|          2022-12-25       |     Sunday       |
|          2022-12-31       |     Saturday     |

如果您能告诉我获取该数据框的最佳方法,我将不胜感激。

好吧,这是我完成的代码。我认为你没有工作,因为你没有写任何东西。

from datetime import datetime
from datetime import timedelta
import calendar
import pandas as pd
import numpy as np


def daysInYear(year):
    beginningOfYear = datetime.strptime(f"{year}",r"%Y")
    days = []
   
    for day_offset in range(365+calendar.isleap(year)):
        today = beginningOfYear+timedelta(days=day_offset,hours=1)
        days.append(today)
    return pd.Series(days)
def get_saturdays_and_sundays(year):

    daysInYearAndDayOfWeek = pd.DataFrame({"Date":daysInYear(year)})
    daysInYearAndDayOfWeek["Day Of The Week"] = daysInYearAndDayOfWeek["Date"].map(lambda date: calendar.day_name[date.weekday()])
    
    return daysInYearAndDayOfWeek[(daysInYearAndDayOfWeek["Day Of The Week"]=="Saturday") | (daysInYearAndDayOfWeek["Day Of The Week"]=="Sunday")]
    
x = get_saturdays_and_sundays(2018)
print(x)