120 字
1 分钟
关于pandas.to_datetime对不同时间格式使用时发生报错的情况
https://dreaife-team.atlassian.net/browse/DREAITE-39
在看菜鸟的pandas对格式错误清洗时,发现菜鸟提供的代码在我现在的版本跑不通。
把报错在网上找了半天都是把报错errors参数给修改的。
最后重看了下报错信息,发现把format改成mixed,告诉pandas数据格式混合就可以(汗),应该是python3版本太新的问题
报错代码:
import pandas as pd
# 第三个日期格式错误data = { "Date": ['2020/12/01', '2020/12/02' , '20201226'], "duration": [50, 40, 45]}
df = pd.DataFrame(data, index = ["day1", "day2", "day3"])
df['Date'] = pd.to_datetime(df['Date'])
print(df.to_string())错误信息:
ValueError: time data "20201226" doesn't match format "%Y/%m/%d", at position 2. You might want to try: - passing `format` if your strings have a consistent format; - passing `format='ISO8601'` if your strings are all ISO8601 but not necessarily in exactly the same format; - passing `format='mixed'`, and the format will be inferred for each element individually. You might want to use `dayfirst` alongside this.修复代码:
import pandas as pd
# 第三个日期格式错误data = { "Date": ['2020/12/01', '2020/12/02' , '20201226'], "duration": [50, 40, 45]}df = pd.DataFrame(data, index = ["day1", "day2", "day3"])
df['Date'] = pd.to_datetime(df['Date'], format='mixed')# df['Date'] = pd.to_datetime(df['Date'],format="%Y/%m/%d",errors='ignore')
print(df.to_string()) 分享
如果这篇文章对你有帮助,欢迎分享给更多人!
关于pandas.to_datetime对不同时间格式使用时发生报错的情况
https://dreaife.tokyo/pandas-datetime-fix/ 部分信息可能已经过时
相关文章 智能推荐
1
Ubuntu通过nat将网络转发给路由器
踩坑 在 Ubuntu 上配置 Netplan 静态 IP、IP 转发、DHCP 与 NAT 规则,将主机网络共享给路由器,并通过客户端连接验证转发是否生效。
2
ubuntu安装ohMyZsh及其组件
踩坑 在 Ubuntu 安装并配置 Oh My Zsh,涵盖 Zsh、Git、Powerlevel10k、常用插件与 .zshrc 设置,完成主题和命令行增强环境。
3
阿里云配置docker+code-server实现线上编译器
踩坑 在阿里云服务器上使用 Docker、Nginx 与 code-server 搭建在线 C/C++ 开发环境,涵盖镜像源配置、容器启动、编译工具链安装和测试代码运行。
4
missing-semester-class01
研习 Missing Semester Shell 入门笔记,涵盖程序执行、路径导航、文件权限、管道与输入输出重定向、root 权限,并附 Bash 命令示例和练习。
5
csapp 第一章 计算机系统漫游
研习 《深入理解计算机系统》第一章笔记:从信息表示和编译系统出发,串联处理器、缓存、操作系统、进程、虚拟内存、并发与抽象等核心概念。





