[英]How can I parse pandas datetime values which are in an inconsitent date format into a uniform date format?
我在 dataframe 中有日期时间值,它们具有不同的格式,即有些格式为yyyy-mm-dd
,有些格式为yyyy-dd-mm
。 我想将它们全部转换为一种格式yyyy-mm-dd
。 该问题仅存在几个月且日期最多为 12 即2021-03-09
记录为2021-09-03
或2021-04-06
记录为2021-06-04
, 2019-11-12
记录为2019-12-11
等。现在我的数据具有一种独特的品质,所有这些数据都记录在星期二,因此这一天必须始终是星期二,因此错误表示的数据将具有不属于星期二的日期。 我尝试像这样创建解析 function
import datetime
def parse_date(date):
if date.weekday() != 1:
year,day,month = date.strftime("%Y-%m-%d").split('-')
else:
year, month,day = date.strftime("%Y-%m-%d").split('-')
return datetime.date(year=int(year), month=int(month), day=int(day))
score["date"] = score.date.apply(parse_date)
我收到以下错误ValueError: month must be in 1..12
我认为这是因为误报日期的mm
超过 12
如何更正错误陈述的日期?
将to_datetime
与format
和errors='coerce'
参数一起使用,因此如果没有匹配项,则存在缺失值,并通过在numpy.where
中比较Tuesday
s 来设置新列:
score = pd.DataFrame({'date':['2021-06-04','2019-11-12','2021-03-09']})
d1 = pd.to_datetime(score.date, format="%Y-%m-%d", errors='coerce')
d2 = pd.to_datetime(score.date, format="%Y-%d-%m", errors='coerce')
#if both are Tuesdays is prioritize `d1`
score["date"] = np.where(d1.dt.weekday == 1, d1, d2)
print (score)
date
0 2021-04-06
1 2019-11-12
2 2021-03-09
也可以比较d2
:
#if both are Tuesdays is prioritize `d2`
score["date"] = np.where(d2.dt.weekday == 1, d2, d1)
print (score)
date
0 2021-04-06
1 2019-11-12
2 2021-03-09
编辑:
score = pd.DataFrame({'date':['2021-06-04','2019-12-11','2021-03-09']})
d1 = pd.to_datetime(score.date, format="%Y-%m-%d", errors='coerce')
d2 = pd.to_datetime(score.date, format="%Y-%d-%m", errors='coerce')
score["date"] = np.where(d2.dt.weekday == 1, d2, d1)
print (score)
date
0 2021-04-06
1 2019-11-12
2 2021-03-09
score["date"] = np.where(d1.dt.weekday == 1, d1, d2)
print (score)
date
0 2021-04-06
1 2019-11-12
2 2021-03-09
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.