python - 类 datetime.time 不能转换为 pandas 中的日期时间
问题描述
我是来自 R 背景的 Python 新手,我在 pandas 中有以下时间栏
time
09:12:23
09:34:33
10:23:22
11:23:33
我想把它转换成熊猫的时间对象,我在 python 中做以下
df['time'] = pd.to_datetime(df['time']).dt.time
为什么它向我显示以下错误。
class datetime.time is not convertible to datetime
解决方案
如果可能,相同的非日期时间/时间值添加参数errors='coerce'
:
print (df)
time
0 aaaaa
1 09:34:33
2 10:23:22
3 11:23:33
df['time'] = pd.to_datetime(df['time'], errors='coerce').dt.time
print (df)
time
0 NaT
1 09:34:33
2 10:23:22
3 11:23:33
编辑:检查这个值:
print (df[pd.to_datetime(df['time'], errors='coerce').isnull()])
time
0 sdass
编辑1:
可以通过以下方式转换为 timedeltas to_timedelta
- 优点是使用 pandas timedelta函数,该函数不适用于time
s:
df['time'] = pd.to_timedelta(df['time'], errors='coerce')
print (df)
time
0 NaT
1 09:34:33
2 10:23:22
3 11:23:33
推荐阅读
- rstudio - R中的####(四个标签)是什么意思?
- ios - 无法从 Swift 代码中读取自定义 iOS 目标属性键值
- mysql - 生成 10 个随机 id 数字形成字符串中的表
- docker - 不能让 docker-compose 像 dockerfile 一样工作
- python - 字典列表 - 具有列表索引的函数超出范围
- pyspark - Spark Sql Pivot 问题 - 列不可迭代
- c - 为什么此代码有效且不会产生分段错误?
- javascript - next.js 简单路由菜单
- asp.net-core-2.1 - .Net Core 项目参考继承
- android - 在 Kotlin 中将 Singleton Service 转换为对象会使我的应用程序崩溃