gpt4 book ai didi

python - 如何将带有 Excel Serial Dates 和常规日期的列转换为 Pandas 日期时间?

转载 作者:行者123 更新时间:2023-12-04 12:32:59 24 4
gpt4 key购买 nike

我有一个数据框,其中有些生日的日期与 Excel 序列日期混合在一起,如下所示:

09/01/2020 12:00:00 AM
05/15/1985 12:00:00 AM
06/07/2013 12:00:00 AM
33233
26299
29428
我尝试了来自 this answer 的解决方案, 并且所有 Excel 串行格式的日期都将被清除,同时保留那些处于正常日期格式的日期。
这是我的代码:
import pandas as pd
import xlrd
import numpy as np
from numpy import *
from numpy.core import *
import os
import datetime
from datetime import datetime, timedelta
import glob

def from_excel_ordinal(ordinal, _epoch0=datetime(1899, 12, 31)):
if ordinal >= 60:
ordinal -= 1 # Excel leap year bug, 1900 is not a leap year!
return (_epoch0 + timedelta(days=ordinal)).replace(microsecond=0)

path = 'C:\\Input'
os.chdir(path)
filelist = glob.glob('*BLAH*.xlsx')
filename = os.fsdecode(filelist[0])
df = pd.read_excel(filename, sheet_name = 'Blah Blah')
m = df['Birthday'].astype(str).str.isdigit()
df.loc[m, 'Birthday'] = df.loc[m, 'Birthday'].astype(int).apply(from_excel_ordinal)
df['Birthday'] = pd.to_datetime(df['Birthday'], errors = 'coerce')

我不确定我哪里出错了,因为代码不应该像现在这样将生日消隐。

最佳答案

  • 无法以相同的方式解析所有日期
  • 加载数据帧
  • dates列作为 str如果还没有。
  • 使用 Boolean Indexing选择不同的日期类型
  • 假设常规日期 contain /
  • 假设 Excel 序列日期不包含 /

  • 根据日期时间类型单独修复每个数据帧
  • Concat数据帧重新组合在一起。

  • import pandas as pd
    from datetime import datetime

    # load data
    df = pd.DataFrame({'dates': ['09/01/2020', '05/15/1985', '06/07/2013', '33233', '26299', '29428']})

    # display(df)

    dates
    0 09/01/2020
    1 05/15/1985
    2 06/07/2013
    3 33233
    4 26299
    5 29428

    # set the column type as a str if it isn't already
    df.dates = df.dates.astype('str')

    # create a date mask based on the string containing a /
    date_mask = df.dates.str.contains('/')

    # split the dates out for excel
    df_excel = df[~date_mask].copy()

    # split the regular dates out
    df_reg = df[date_mask].copy()

    # convert reg dates to datetime
    df_reg.dates = pd.to_datetime(df_reg.dates)

    # convert excel dates to datetime; the column needs to be cast as ints
    df_excel.dates = pd.TimedeltaIndex(df_excel.dates.astype(int), unit='d') + datetime(1900, 1, 1)

    # combine the dataframes
    df = pd.concat([df_reg, df_excel])
    显示(df)
           dates
    0 2020-09-01
    1 1985-05-15
    2 2013-06-07
    3 1990-12-28
    4 1972-01-03
    5 1980-07-28

    关于python - 如何将带有 Excel Serial Dates 和常规日期的列转换为 Pandas 日期时间?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63963635/

    24 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com