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

如何将DataFrame中%m-%d格式的日期字符串转换为dayofyear格式?

Hey there! Let's figure out how to convert those '%m-%d' date strings to day-of-year values in your pandas DataFrame. It's actually pretty straightforward with pandas' built-in datetime tools—here's a step-by-step breakdown:

Step 1: Convert the string column to datetime objects

First, we need to turn those '%m-%d' strings into proper datetime entries. Since your dates don't include a year, pandas will automatically use the current year by default. If you want to use a specific year (like handling leap years for February 29), you can explicitly set it with the year parameter.

Example code to get started:

import pandas as pd

# Your sample DataFrame
df = pd.DataFrame({'month_day': ['01-01', '02-28', '03-15', '12-31', '02-29']})

# Option 1: Use current year (default behavior)
df['date'] = pd.to_datetime(df['month_day'], format='%m-%d')

# Option 2: Specify a fixed year (e.g., 2024, a leap year)
df['date_fixed'] = pd.to_datetime(df['month_day'], format='%m-%d', year=2024)

Step 2: Extract the day-of-year value

Once you have datetime objects, you can use the .dt.dayofyear attribute to get the day number (1 to 365/366):

# Get dayofyear for both date columns
df['dayofyear_current'] = df['date'].dt.dayofyear
df['dayofyear_fixed'] = df['date_fixed'].dt.dayofyear

Handling edge cases: Invalid dates

If your data has dates like '02-29' and you're using a non-leap year (e.g., 2023), pandas will throw an error by default. To handle this gracefully, add errors='coerce' to convert invalid dates to NaT (Not a Time), which will result in NaN for the day-of-year value:

# Safe conversion with error handling
df['date_safe'] = pd.to_datetime(df['month_day'], format='%m-%d', year=2023, errors='coerce')
df['dayofyear_safe'] = df['date_safe'].dt.dayofyear

Example output

If you print the final DataFrame, you'll see something like this:

month_daydatedate_fixeddayofyear_currentdayofyear_fixeddate_safedayofyear_safe
01-012024-01-012024-01-01112023-01-011
02-282024-02-282024-02-2859592023-02-2859
03-152024-03-152024-03-1575752023-03-1574
12-312024-12-312024-12-313663662023-12-31365
02-292024-02-292024-02-296060NaTNaN

Notice how '03-15' has different day-of-year values in 2023 (non-leap) vs 2024 (leap)—that's why specifying a fixed year can be important depending on your use case!

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.27 09:48:02