我有一个日期列,格式如下:
Jan-85
Apr-99
Nov-01
Feb-65
Apr-57
Dec-19
我想把它转换成一个pandas datetime对象。
以下语法用于转换它们:
pd.to_datetime(temp, format='%b-%y')
其中temp
是日期的pd.Series对象。当然,这里最突出的问题是1970年之前的日期被错误地转换为20xx。
我尝试使用以下参数更新函数调用:
pd.to_datetime(temp, format='%b-%y', origin='1950-01-01')
然而,我得到了一个错误:
Name: temp, Length: 42537, dtype: object' is not compatible with origin='1950-01-01'; it must be numeric with a unit specified
我试着像它说的那样指定一个单位,但我得到了一个不同的错误,指出单位不能与格式一起指定。
有什么办法解决这个问题吗?
发布于 2021-03-14 13:57:01
只是@DudeWah的逻辑,但对代码进行了改进:
def days_of_future_past(date,chk_y=pd.Timestamp.today().year):
return date.replace(year=date.year-100) if date.year > chk_y else date
temp = pd.to_datetime(temp,format='%b-%y').map(days_of_future_past)
输出:
>>> temp
0 1985-01-01
1 1999-04-01
2 2001-11-01
3 1965-02-01
4 1957-04-01
5 2019-12-01
6 1965-05-01
Name: date, dtype: datetime64[ns]
发布于 2021-03-14 12:36:03
我将继续回答我自己的问题,以便其他人在遇到同样的问题时可以使用此解决方案。不是最好的,但它可以完成工作。它应该可以工作到2069年,所以希望到那时熊猫会有一个更好的解决方案
也许其他人会发布更好的解决方案。
def wrong_date_preprocess(data):
"""Correct date issues with pre-1970 dates with whacky mon-yy format."""
df1 = data.copy()
dates = df1['date_column_of_interest']
# use particular datetime format with data; ex: jan-91
dates = pd.to_datetime(dates, format='%b-%y')
# look at wrongly defined python dates (pre 1970) and get indices
date_dummy = dates[dates > pd.Timestamp.today().floor('D')]
idx = list(date_dummy.index)
# fix wrong dates by offsetting 100 years back dates that defaulted to > 2069
dummy2 = date_dummy.apply(lambda x: x.replace(year=x.year - 100)).to_list()
dates.loc[idx] = dummy2
df1['date_column_of_interest'] = dates
return(df1)
https://stackoverflow.com/questions/66620553
复制相似问题