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

使用datetime库提取多列年份,实现Pandas日期转年份差值函数

Handling Date Columns in Pandas: Extracting Years and Calculating Year Differences

Let's break down your two requirements into actionable, clean code solutions, building on the function snippet you provided.

1. Extracting Year from Multiple Date Columns

Whether your date columns are already datetime objects or stored as strings in %b-%Y format, here's how to extract the year using pandas and the datetime library:

For Existing Datetime Columns

If your columns are already converted to datetime type, use the .dt.year accessor to pull out just the year value:

import pandas as pd

# List of your datetime columns
date_cols = ['hire_date', 'birth_date']

for col in date_cols:
    # Create a new column with the extracted year
    df[f'{col}_year'] = df[col].dt.year

For String Columns in %b-%Y Format

First convert the string dates to datetime objects, then extract the year:

for col in date_cols:
    # Convert string to datetime (specify format for faster, accurate parsing)
    df[col] = pd.to_datetime(df[col], format='%b-%Y')
    # Extract year into a new column
    df[f'{col}_year'] = df[col].dt.year

2. Complete Function to Convert %b-%Y Dates to Year Difference

Here's the polished, functional version of your snippet that converts date columns to the difference between the current year and the date's year. I've added error handling and clarity for production use:

import pandas as pd

def date_to_numeric(df, date_columns):
    # Get current year dynamically (no hardcoding required!)
    current_year = pd.Timestamp.now().year
    
    for col in date_columns:
        print(f"Converting date variable: {col}", flush=True)
        
        # Convert string dates to datetime, coercing invalid values to NaT
        df[col] = pd.to_datetime(df[col], format='%b-%Y', errors='coerce')
        
        # Calculate year difference, replacing invalid dates with a placeholder (-1)
        df[col] = current_year - df[col].dt.year.fillna(-1).astype(int)
    
    return df

How to Use This Function

Suppose your DataFrame has columns 'join_date' and 'expiry_date' in %b-%Y format:

# Example DataFrame
data = {
    'join_date': ['Jun-2017', 'Apr-2019', 'Jan-2020'],
    'expiry_date': ['Dec-2025', 'Mar-2023', 'InvalidDate']
}
df = pd.DataFrame(data)

# Apply the function to your date columns
df = date_to_numeric(df, date_columns=['join_date', 'expiry_date'])

Key Notes

  • errors='coerce' ensures invalid date strings are converted to NaT (Not a Time), which we replace with -1 (adjust this placeholder to fit your use case).
  • pd.Timestamp.now().year automatically grabs the current year, so your code stays up-to-date without manual changes.
  • To preserve original date columns, modify the function to create new columns instead of overwriting, e.g., df[f'{col}_year_diff'] = current_year - df[col].dt.year.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.22 09:52:18