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

自动识别CSV/Excel文件中未知名称位置的datetime时间列方法求助

自动识别DataFrame中的datetime时间列方法

核心思路

  • 先筛选所有object类型的列,排除数值、布尔等肯定不是时间格式的列
  • 对每个object列尝试转换为datetime格式,统计转换成功率
  • 可选增加时序逻辑校验,排除偶然符合时间格式的普通字符串列

代码实现

import pandas as pd

# 读取你的文件,Excel对应改用pd.read_excel即可
df = pd.read_csv("你的文件路径.csv")

# 筛选所有object类型的列
object_cols = df.select_dtypes(include=['object']).columns.tolist()

# 基础版时间列判断函数
def is_datetime_col(col, threshold=0.9):
    # 尝试转换为datetime,转换失败的取值为NaT空值
    converted = pd.to_datetime(col, errors='coerce')
    # 计算转换成功的比例
    success_rate = converted.notna().mean()
    return success_rate >= threshold

# 进阶版时间列判断函数,增加时序单调性校验,进一步降低误判率
def is_datetime_col_advanced(col, threshold=0.9, check_order=True):
    converted = pd.to_datetime(col, errors='coerce')
    success_rate = converted.notna().mean()
    if success_rate < threshold:
        return False
    if check_order:
        # 校验时间列是否单调递增或递减,符合绝大多数业务场景的时间列特征
        return converted.is_monotonic_increasing or converted.is_monotonic_decreasing
    return True

# 识别时间列
datetime_cols = [col for col in object_cols if is_datetime_col_advanced(df[col])]

# 输出识别到的时间列
print(datetime_cols)

参数说明

  • threshold:转换成功率阈值,规整无缺失的时间列可设为1,存在少量脏数据的场景可下调到0.8~0.9
  • check_order:是否校验时间序列的单调性,大部分业务场景下的时间列都是按顺序排列的,开启后可大幅降低误判概率

验证效果

针对你提供的CSV示例,上述方法会准确识别出timestep列为唯一的datetime时间列。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.05 20:12:03