python - 当索引同时是时间戳和日期时间时,将所有索引值转换为日期时间
问题描述
我想将我的时间序列 DataFrame 的索引转换为日期时间。问题是一些索引是时间戳和一些日期时间。
time C1
2020-10-18 13:38:43.349 0.046
2020-10-18 13:52:34.104 0.099
1602824859304 1.000
1602824934121 0.007
这: df['time'] = pd.to_datetime(df['time'], unit='ms')
产量: ValueError: non convertible value time with the unit 'ms'
这: df["time"] = df["time"].apply(lambda x: pd.to_datetime(x,errors='ignore').strftime('%Y-%m-%d %H:%M') if len(x) !=0 else "----")
产量: AttributeError: 'str' object has no attribute 'strftime'
这是一个类似的问题,但不适用于我的情况:
Convert dataframe column to datetime only if string of length is not zero
我的预期输出是所有索引行都是日期时间格式。
解决方案
让我们尝试识别所有时间戳的行并分别转换它们:
mask = df['time'].str.contains(' ')
df['time'] = (pd.to_datetime(df.loc[mask,'time'])
.reindex(df.index)
.fillna(pd.to_datetime(df.loc[~mask, 'time'], unit='ms'))
)
输出:
time C1
0 2020-10-18 13:38:43.349 0.046
1 2020-10-18 13:52:34.104 0.099
2 2020-10-16 05:07:39.304 1.000
3 2020-10-16 05:08:54.121 0.007
推荐阅读
- jsp - 是否可以通过 jsp 和 Servlet 从数据库中提取选定的行?
- java - 我在哪里可以在骆驼组件中实现转换器?
- apache-spark - 带有where子句的pyspark sql抛出列不存在错误
- android - 从 targetSdkVersion 21 更改为 targetSdkVersion 26 时出错
- c# - 如何使用 selenium-c# 框架通过自动化验证 HTML?
- java - 错误:不兼容的类型:从double到int的可能有损转换如何解决
- dart - 如何使颤动的TextField高度匹配容器的父级?
- sql - 使用 3 个参数创建 TYPE
- c++ - 代码注入不能与 FILE* 一起用于日志记录
- angular - 找不到模块“。” 在构建产品版本时