我有一个包含日期列的 .csv 文件,日期如下所示。
date
2016年 4月 1日 <-- there are whitespaces in thie row
...
2016年10月10日
日期格式为日文日期格式。我正在尝试将此列转换为“YYYY-MM-DD”,我正在使用的 python 代码如下。
data['date'] = [datetime.datetime.strptime(d, '%Y年%m月%d日').date() for d in data['date']]
有一个问题,当月/日为一位数时,.csv 中的日期列可能包含空格。当有空格时,我的代码无法正常工作。
有人解决吗?
最佳答案
如果存在矢量化解决方案,在 pandas 中最好避免列表理解,因为性能不支持 NaN
s。
我认为需要replace
by \s+
: 一个或多个空格 pandas.to_datetime
转换为日期时间和最后的日期添加 date
:
data['date'] = (pd.to_datetime(data['date'].str.replace('\s+', ''), format='%Y年%m月%d日')
.dt.date)
性能:
该图是用 perfplot 创建的:
def list_compr(df):
df['date1'] = [datetime.datetime.strptime(d.replace(" ", ""), '%Y年%m月%d日').date() for d in df['date']]
return df
def vector(df):
df['date2'] = (pd.to_datetime(df['date'].str.replace('\s+', ''), format='%Y年%m月%d日').dt.date)
return df
def make_df(n):
df = pd.DataFrame({'date':['2016年 4月 1日','2016年10月10日']})
df = pd.concat([df] * n, ignore_index=True)
return df
perfplot.show(
setup=make_df,
kernels=[list_compr, vector],
n_range=[2**k for k in range(2, 13)],
logx=True,
logy=True,
equality_check=False, # rows may appear in different order
xlabel='len(df)')
关于python datetime 转换,日期可能包含空格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51345286/