如何将datetime64[D]类型的date_index转换为月份名称?
Hey there! You’ve already got your datetime64[D] date sequence set up, so let’s break down how to convert it to both month numbers (1-12) and month names. I’ll cover pure NumPy methods and more intuitive Pandas approaches—pick what fits your workflow!
1. Convert to Month Numbers (1-12)
Option 1: Pure NumPy Implementation
You can leverage NumPy’s datetime64 type directly to extract month values:
import numpy as np # Your existing date sequence date_index = np.arange('2015-01-01','2016-01-01', dtype='datetime64[D]') # Convert to month numbers (1 to 12) month_numbers = (date_index.astype('datetime64[M]').astype(int) % 12) + 1
Here’s the breakdown: We first cast the dates to month precision (datetime64[M]), convert those to integers, take modulo 12 to wrap around the year, then add 1 to shift from 0-11 to 1-12.
Option 2: Pandas (More Readable)
If you’re already using Pandas in your project, this method is cleaner and easier to follow:
import numpy as np import pandas as pd date_index = np.arange('2015-01-01','2016-01-01', dtype='datetime64[D]') # Convert to Pandas DatetimeIndex pd_dates = pd.DatetimeIndex(date_index) # Grab month numbers directly month_numbers = pd_dates.month
2. Convert to Month Names (e.g., "January", "Feb")
Pandas really shines here with built-in methods for month names, but I’ll also include a pure NumPy option if you want to avoid dependencies.
Option 1: Pandas for English Month Names
Get full names or abbreviations with just a couple lines:
import numpy as np import pandas as pd date_index = np.arange('2015-01-01','2016-01-01', dtype='datetime64[D]') pd_dates = pd.DatetimeIndex(date_index) # Full month names (e.g., "January", "February") full_month_names = pd_dates.month_name() # Shortened month names (e.g., "Jan", "Feb") short_month_names = pd_dates.month_abbr
Bonus: If you need month names in another language, you can set the locale (e.g., pd_dates.month_name(locale='fr_FR') for French).
Option 2: Pure NumPy (Custom Mapping)
If you don’t want to use Pandas, create a month name mapping and match it to your month numbers:
import numpy as np date_index = np.arange('2015-01-01','2016-01-01', dtype='datetime64[D]') # First get month numbers using the NumPy method above month_numbers = (date_index.astype('datetime64[M]').astype(int) % 12) + 1 # Define your month name list (index 0 is unused to match 1-12) month_name_map = [ "", "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December" ] # Map numbers to names month_names = np.array(month_name_map)[month_numbers]
内容的提问来源于stack exchange,提问作者Razieh Delavar

