首页 > 解决方案 > csv文件中多列的python pandas parse_dates

问题描述

我正在使用 Python pandas 来比较两个 csv 文件,但是在具有 5 个日期列的 csv 文件中,我在 read_csv 方法中使用了 parse_date=['dateofbirth','lastupdates','dateofjoin','dateofresign,'endoftrade'] 但是它只是解析 dateofbirth 而不是 csv 文件中的所有列。

代码:

csv_pandas=pd.read_csv("path of the csv file",parse_date=['dateofbirth','lastupdates','dateofjoin','dateofresign,'endoftrade'])
print(csv_pandas)

CSV 文件:

dateofbirth             lastupdates       dateofjoin          dateofresign 
05/06/2021 00:00:00PM 12/13/2021 12:00:00PM 12/13/2021 12:00:00PM 12/13/2021 12:00:00PM

column        non-null count   Dtype
------        -------------    ------
dateofbirth    non-null         object
dateofbirth    non-null         datetime64[ns]
dateofbirth    non-null         datetime64[ns]
dateofbirth    non-null         datetime64[ns]

我只能转换对象 Dtype 列,剩余的 datetime64[ns] 不解析

大约我有 160 个 csv 文件,每个 csv 文件都有不同的列名,任何人都可以建议

标签: pythonpandascsv

解决方案


  • 您有两种需要不同strptime()格式说明的日期格式。
  • 并非您尝试转换的所有列都存在于数据框中,因此测试该列存在于作为 ** kwargs传递的dict理解中assign()
csv_pandas = csv_pandas.assign(
    **{
        c: pd.to_datetime(csv_pandas[c], format="%Y-%m-%d %H:%M:%S:%f", errors="ignore")
        for c in parse_date
        if c in csv_pandas.select_dtypes("object").columns
    }
).pipe(
    lambda d: d.assign(
        **{
            c: pd.to_datetime(d[c], format="%m/%d/%Y %H:%M:%S%p", errors="ignore")
            for c in parse_date
            if c in d.select_dtypes("object").columns
        }
    )
)

输出

csv_pandas.dtypes
dateofbirth     datetime64[ns]
lastupdates     datetime64[ns]
dateofjoin      datetime64[ns]
dateofresign    datetime64[ns]
dtype: object

推荐阅读