You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何生成标记日期是否为每月第三个周五的Pandas Series

How to Create a Pandas Series Indicating Third Fridays of the Month

Great approach starting with a 0-filled Series and updating the relevant dates—let's flesh that out into a complete, clean solution. Here's how to implement it efficiently:

First, we'll generate your date range, then create the initial Series. Then we'll use Pandas' built-in datetime properties to identify the third Fridays and update their values to 1.

import pandas as pd

# Generate 8 years of dates
dates = pd.date_range("2010-01-01", "2017-12-31")

# Create initial Series with all 0s
third_fridays = pd.Series(0, index=dates)

# Identify dates that are the third Friday of their month
# - dt.dayofweek == 4 means Friday (Pandas uses 0 for Monday, 4 for Friday)
# - dt.day between 15 and 21 ensures it's the third occurrence (first Fri: 1-7, second:8-14, third:15-21)
mask = (dates.dayofweek == 4) & (dates.day >= 15) & (dates.day <= 21)

# Update those positions to 1
third_fridays.loc[mask] = 1

How this works:

  • dates.dayofweek ==4: Filters for all Fridays in the date range.
  • dates.day >=15 & <=21: Narrows down to the third Friday—since the first Friday of a month can’t be later than the 7th, the second falls between 8-14, so the third must land in the 15-21 window.
  • We apply this boolean mask to our Series to set only the third Friday positions to 1.

If you prefer a more concise one-liner (while keeping readability), you can directly convert the boolean mask to integers (True →1, False→0) instead of starting with 0s:

third_fridays = pd.Series(
    ((dates.dayofweek == 4) & (dates.day.between(15, 21))).astype(int),
    index=dates
)

Either approach works perfectly—pick whichever you find more intuitive for your workflow.

内容的提问来源于stack exchange,提问作者neptunhiker

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.20 12:07:06