如何将DataFrame中mth列的日期值提取为仅保留年份?
Hey there! Let's get your DataFrame's mth column simplified to just the year. Below are practical approaches based on what data type your mth column currently is:
Case 1: mth is already a datetime type
If you've already converted the column to pandas datetime format, extracting the year is straightforward with the .dt.year accessor:
import pandas as pd # Replace 'df' with your actual DataFrame name df['mth'] = df['mth'].dt.year
Case 2: mth is a string type (e.g. '1977-01-01')
If your dates are stored as strings, first convert them to datetime to ensure reliable year extraction (this handles most date format variations automatically):
# Convert string column to datetime, then extract year df['mth'] = pd.to_datetime(df['mth']).dt.year
Example with your sample data
Let's test this with a snippet of your data to see the result:
# Sample data matching your structure sample_data = { 'mth': ['1977-01-01', '1977-02-01', '2019-06-01'], 'account_type': ['Special', 'Special', 'Special'], 'interest_rate': [6.5, 6.5, 5] } df = pd.DataFrame(sample_data) # Process the column df['mth'] = pd.to_datetime(df['mth']).dt.year print(df)
Output:
mth account_type interest_rate 0 1977 Special 6.5 1 1977 Special 6.5 2 2019 Special 5.0
Note for custom date formats
If your mth column uses a non-standard date format that pd.to_datetime() can't auto-detect, specify the format explicitly with the format parameter. For example, if dates were in 'DD-MM-YYYY' format:
df['mth'] = pd.to_datetime(df['mth'], format='%d-%m-%Y').dt.year
内容的提问来源于stack exchange,提问作者Lawrence How

