熊猫read_csv解析日期

时间:2019-12-05 11:22:31

标签: python pandas python-datetime

我已经编写了此日期解析功能

def date_parser(string):
   try:
       date = pd.datetime.strptime(string, "%d/%m/%Y")
   except:
       date = pd.NaT
   return date

我这样在p​​d.read_csv中称呼它

df = pd.read_csv(os.path.join(path, file),
                 sep=";",
                 encoding="latin-1",
                 keep_default_na=False,
                 na_values=na_values,
                 index_col=False,
                 usecols=keep,
                 dtype=dtype,
                 date_parser=date_parser,
                 parse_dates=dates)

问题在于,在我的日期列之一中,我最终遇到了混合数据类型

df[data].apply(type).value_counts()
  • 'datetime.datetime'类
  • class'pandas._libs.tslibs.timestamps.Timestamp'
  • class'pandas._libs.tslibs.nattype.NaTType'

我应该只保留最后两个吗?

1 个答案:

答案 0 :(得分:3)

我建议将to_datetimeerrors='coerce'一起更改,以返回NaT的格式,如果格式不匹配%d/%m/%Y

def date_parser(string):
   return pd.to_datetime(string, format="%d/%m/%Y", errors='coerce')