【问题标题】:parsing inconsistent times with pandas用熊猫解析不一致的时间
【发布时间】:2019-02-22 21:44:14
【问题描述】:

我正在使用带有以下代码的 pandas 将多个 excel 文件合并在一起。我在转换“时间”列中的时间时遇到问题。每个电子表格的格式都不同,有些时间为字符串“0900”,而有些时间格式为 9:00。我需要它们都是字符串或时间。

我尝试了以下代码:

df_merge.assign(newtime = pd.to_datetime(df_merge.time).dt.time)

这会将字符串“0900”的值转换为 9:00,但它会将 9:00 的所有时间值都删除为 NaN 的......我该如何处理这里的数据类型差异?

df_merge = pd.DataFrame()
for f in os.listdir(path):
    try:
        df = pd.read_excel(path+"/"+f, header = None, skiprows = 1, 
                        names = ['sys_name','sys_no', 'date','time',
                                    'location','collected_by','date_set','date_comp',
                                    'smpl_type','total','fecal','cl_res','comment','lab_no'],
                        dtype = {'time':str})
        if len(df.columns) != 14:
            print(f, "is not formatted properly. It has", len(df.columns), "row(s) when it should have 14.")
        else:
            df_merge = df_merge.append(df, ignore_index=True)
    except Exception as e:
        print(e)

我还尝试将列转换为字符串并使用 dateutil.parser 进行解析:

df_merge['time'].apply(lambda x: parse(str(x)))

但是对于格式为“0900”的行,我得到了 1325-02-22 00:00:00

时间是这个日期时间中的年份..

【问题讨论】:

  • excel中“0900”的格式是什么? 09:00 是格式日期时间还是字符串?

标签: python pandas time


【解决方案1】:

当我想将 datetime 转换为 str 时,我将使用转换器而不是 dtypes:

df = pd.read_excel(path+"/"+f, header = None, skiprows = 1, 
                    names = ['sys_name','sys_no', 'date','time',
                   'location','collected_by','date_set','date_comp',
                   'smpl_type','total','fecal','cl_res','comment','lab_no'],
                    converters={'time': str})

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-07-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-11-29
    • 2018-11-02
    • 2020-10-19
    • 2022-01-10
    相关资源
    最近更新 更多