如何将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_day | date | date_fixed | dayofyear_current | dayofyear_fixed | date_safe | dayofyear_safe |
|---|---|---|---|---|---|---|
| 01-01 | 2024-01-01 | 2024-01-01 | 1 | 1 | 2023-01-01 | 1 |
| 02-28 | 2024-02-28 | 2024-02-28 | 59 | 59 | 2023-02-28 | 59 |
| 03-15 | 2024-03-15 | 2024-03-15 | 75 | 75 | 2023-03-15 | 74 |
| 12-31 | 2024-12-31 | 2024-12-31 | 366 | 366 | 2023-12-31 | 365 |
| 02-29 | 2024-02-29 | 2024-02-29 | 60 | 60 | NaT | NaN |
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

