我已经编写了此日期解析功能
def date_parser(string):
try:
date = pd.datetime.strptime(string, "%d/%m/%Y")
except:
date = pd.NaT
return date
我这样在pd.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()
我应该只保留最后两个吗?
答案 0 :(得分:3)
我建议将to_datetime
与errors='coerce'
一起更改,以返回NaT
的格式,如果格式不匹配%d/%m/%Y
:
def date_parser(string):
return pd.to_datetime(string, format="%d/%m/%Y", errors='coerce')