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

基于Pandas DataFrame的出生日期拼接及格式转换技术问询

Pandas DataFrame 日期处理解决方案

1. 按条件生成BirthDate字段

可以通过两种简洁方式实现需求:

方法一:使用loc定位赋值

先初始化BirthDate列(可选,避免后续空值问题),再定位符合条件的行拼接日期字符串:

# 初始化列(若已有BirthDate列可忽略)
df['BirthDate'] = ''
# 对BirthDateFlag为'Year'的行生成日期字符串
df.loc[df['BirthDateFlag'] == 'Year', 'BirthDate'] = df['YearOfBirth'].astype(str) + '-01-01'

方法二:使用numpy.where条件赋值

适合同时处理满足/不满足条件的场景,可保留原有值或设置默认值:

import numpy as np
df['BirthDate'] = np.where(
    df['BirthDateFlag'] == 'Year',
    df['YearOfBirth'].astype(str) + '-01-01',
    df.get('BirthDate', '')  # 若已有BirthDate值则保留,否则设为空字符串
)

示例:当YearOfBirth为2001时,生成的BirthDate为'2001-01-01'

2. 转换BirthDate为日期格式

使用pandas.to_datetime方法直接转换,指定格式可提升解析效率:

import pandas as pd
df['BirthDate'] = pd.to_datetime(df['BirthDate'], format='%Y-%m-%d')

如果存在无效日期字符串,可通过errors='coerce'将其转为NaT(缺失时间值):

df['BirthDate'] = pd.to_datetime(df['BirthDate'], format='%Y-%m-%d', errors='coerce')

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.22 22:22:08