Pandas中int类型列转date类型列遇格式匹配错误求助
解决Pandas转换int日期列的问题
错误原因:你使用的
format='%d%m%Y'中,%Y匹配四位年份,但你的数据是两位年份;同时该格式要求日期字符串为8位(两位日+两位月+四位年),而你的数据是5位,导致格式不匹配报错。正确处理步骤:
- 将int类型列转为字符串,避免前导零丢失:
df['Date'] = df['Date'].astype(str) - 补全月份为两位(你的月份是一位数,需补零到两位,保证总长度为6位:两位日+两位月+两位年):
比如# 拆分日、月、年并补零拼接 df['Date_formatted'] = df['Date'].str[:2] + df['Date'].str[2:3].str.zfill(2) + df['Date'].str[3:]'10712'会被处理为'100712',对应日10、月07、年12。 - 使用
%y(匹配两位年份)进行日期转换:df_date = pd.to_datetime(df['Date_formatted'], format='%d%m%y')
- 将int类型列转为字符串,避免前导零丢失:
简化写法(合并步骤):
df_date = pd.to_datetime( df['Date'].astype(str).str[:2] + df['Date'].astype(str).str[2:3].str.zfill(2) + df['Date'].astype(str).str[3:], format='%d%m%y' )
注意:如果你的数据中存在月份是两位的情况(比如101212表示日10、月12、年12),上述补零操作不会影响它,因为str.zfill(2)对已经是两位的字符串无效。
内容的提问来源于stack exchange,提问作者txmai
相关产品推荐
相关产品推荐

