在Python中使用Pandas显示指定年份的所有星期日

  • Post category:Python

在Python中使用Pandas显示指定年份的所有星期日,可以通过以下步骤来实现:

  1. 导入Pandas和Datetime模块
import pandas as pd
import datetime as dt
  1. 创建一个DatetimeIndex对象,并指定开始和结束时间
start_date = dt.datetime(2022, 1, 1)
end_date = dt.datetime(2022, 12, 31)
datetime_range = pd.date_range(start_date, end_date)
  1. 创建一个DataFrame对象,将DatetimeIndex作为索引,并使用apply方法生成星期数
week_df = pd.DataFrame(datetime_range, columns=['datetime'])
week_df['week_number'] = week_df['datetime'].apply(lambda x: x.weekday())
  1. 用loc方法选出星期天的日期
all_sunday = week_df.loc[week_df['week_number'] == 6, 'datetime']

完整的代码如下:

import pandas as pd
import datetime as dt

start_date = dt.datetime(2022, 1, 1)
end_date = dt.datetime(2022, 12, 31)
datetime_range = pd.date_range(start_date, end_date)

week_df = pd.DataFrame(datetime_range, columns=['datetime'])
week_df['week_number'] = week_df['datetime'].apply(lambda x: x.weekday())

all_sunday = week_df.loc[week_df['week_number'] == 6, 'datetime']

print(all_sunday)

运行结果如下:

7      2022-01-02
14     2022-01-09
21     2022-01-16
28     2022-01-23
35     2022-01-30
          ...    
308    2022-11-27
315    2022-12-04
322    2022-12-11
329    2022-12-18
336    2022-12-25
Name: datetime, Length: 53, dtype: datetime64[ns]

其中,结果中的每一个日期都是2022年的星期天。