【问题标题】:Pandas KeyError Date when date is a string日期为字符串时的 Pandas KeyError 日期
【发布时间】:2020-07-14 21:23:10
【问题描述】:

我有一个包含数十万行的制表符分隔的 .txt 文件。其中一列是“日期”,日期格式是“14JAN2020”,这是非标准的。我正在尝试将其转换为标准日期时间。到目前为止我的代码:

import pandas as pd
import datetime as dt
import numpy as np
import matplotlib.pyplot as plt

with open('C:/Path/to/file/myfile.txt') as completionFile:
     completionFile.read()

df = pd.read_csv('C:/Path/to/file/myfile.txt', sep='\t', header=0)
df.head()

工作ID |员工编号 |日期 |工作类型 |工作时间

1234 | ABCD | 2020 年 1 月 14 日 |富 |酒吧

df["date"] = df['date'].str.replace(r'^((?:\D*\d){2})', r'\1-')
df["date"] = df['date'].str.replace(r'^((?:[^a-zA-Z0-9]*[a-zA-Z0-9]){5})(?=.+)', r'\1-')
df["date"] =pd.to_datetime(df['date'])

当我这样做时,我得到 KeyError: 'date'。我将“日期”作为列标题,而不是作为索引,所以我很纠结为什么会在这里出现此错误

【问题讨论】:

    标签: pandas datetime keyerror


    【解决方案1】:

    使用pd.to_datetime 将日期强制转换为日期时间并说明日期时间格式。

       print(df)
        job-id employee_id       date        job_type job_time
    0    1234        ABCD        14JAN2020      foo      bar
    
    
    
    
    df['date']=pd.to_datetime(df['date'])
    #df['date']=pd.to_datetime(df['date'], format='%Y%m%d')
    print(df)
         job-id employee_id       date           job_type job_time
    0    1234        ABCD         2020-01-14      foo      bar
    

    【讨论】:

    • 谢谢@wwnde!这为我节省了一大堆字符串替换。错误的原因是我在原始 .txt 文件中有一个看不见的标题行,所以我消除了它,然后使用了您的解决方案
    猜你喜欢
    • 1970-01-01
    • 2021-07-11
    • 2017-12-14
    • 1970-01-01
    • 2016-05-03
    • 2020-08-26
    • 1970-01-01
    • 2022-07-04
    • 1970-01-01
    相关资源
    最近更新 更多