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

如何将日期列与含空值的时间列合并为datetime类型?

解决DataFrame含空值的时间列转换问题

问题根源是time_start列的空值与date字符串拼接后,生成了无效的时间格式字符串,导致pd.to_datetime解析失败。以下是几种可行的解决方案:

方案1:使用errors='coerce'参数(最简单)

直接给pd.to_datetime添加errors='coerce'参数,将无法解析的内容(包括空值拼接的无效字符串)转为时间类型的空值NaT:

df['time_start'] = pd.to_datetime(df['date'].astype(str) + ' ' + df['time_start'].astype(str), errors='coerce')

这个参数会跳过解析错误,同时保留所有能正常转换的时间值。

方案2:针对性处理非空行

先初始化列为NaT,只对time_start非空的行执行拼接转换:

# 先把整列设为时间类型空值
df['time_start'] = pd.NaT
# 筛选出time_start非空的行
non_null_mask = df['time_start'].notna()
# 仅对这些行进行时间转换
df.loc[non_null_mask, 'time_start'] = pd.to_datetime(
    df.loc[non_null_mask, 'date'].astype(str) + ' ' + df.loc[non_null_mask, 'time_start'].astype(str)
)

这种方式更可控,避免生成无效的拼接字符串。

方案3:利用datetime.combine高效组合(推荐)

由于date已经是datetime类型,无需字符串拼接,直接用datetime.combine组合日期和时间,空值自动转为NaT:

from datetime import datetime

df['time_start'] = df.apply(
    lambda row: datetime.combine(row['date'], pd.to_datetime(row['time_start']).time()) 
    if pd.notna(row['time_start']) 
    else pd.NaT,
    axis=1
)

这种方法避免了字符串操作的性能损耗,更符合datetime类型的原生处理逻辑。

内容的提问来源于stack exchange,提问作者Con-cat-enate

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.18 01:45:36