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

Pandas日期时间转换:仅对无时间值的行输出纯日期格式

解决方案

你可以使用numpy.where做条件分支处理,仅对l_time为空的行执行00:00的替换操作,完整代码如下:

import pandas as pd
import numpy as np

# 原始DataFrame构造
df = pd.DataFrame(
    {
            'ID': ['AB01', 'AB02', 'AB03', 'AB04','AB05', 'AB06'],
            'l_date': ["1/4/2021","1/4/2021",'1/5/2021','1/5/2021','1/8/2021', np.nan],
            'l_time': ["17:05","6:00","13:43:10","00:00",np.nan,np.nan]
    }
)

# 原有基础处理逻辑
cols = ['l_date','l_time']
df['d_datetime'] = df[cols].astype(str).agg(' '.join, axis=1)
df['d_datetime'] = df['d_datetime'].replace({'nan':''},  regex=True) 
df['d_datetime'] = pd.to_datetime(df['d_datetime'], errors="coerce").dt.strftime("%d/%m/%Y %H:%M")

# 新增条件替换逻辑,仅l_time为空时删除00:00后缀
df['d_datetime'] = np.where(
    df['l_time'].isna(),
    df['d_datetime'].str.replace(r'\s00:00$', '', regex=True),
    df['d_datetime']
)

运行后最终d_datetime列输出符合预期:

  • AB04原l_time为00:00,结果保留完整的05/01/2021 00:00
  • AB05原l_time为空,结果仅保留日期08/01/2021
  • 其余行和空值行的输出逻辑保持不变

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.28 21:54:08