python - 在 pandas df 中查找所有时间戳列并将其转换为数据时间
问题描述
我有一个 df,它在以下格式中有几列时间图
2021-01-21T12:25:21.000Z
转换为日期时间
pd.Series(df.lastModifiedDate).astype('datetime64[ms]')
2021-01-21 12:25:21
有什么方法可以一次转换所有时间戳列而不手动指定每一列?
只有突出显示的一个是时间戳
解决方案
您可以通过测试一行中每一列的格式来收集列名。也就是说,如果列值的字符串与某个模式匹配,则将该列添加到列列表中
# if the pattern is more complex, replace with regex or longer pattern
dtcols = [c for c in df.columns if str(df.iloc[0, df.columns.get_loc(c)]).endswith('0Z')]
# use to_datetime rather than astype, you have more control over conversion
df.loc[:, dtcols] = pd.to_datetime(df.loc[:, dtcols], errors='coerce')
推荐阅读
- c# - 使用新的 .NET SDK Azure.Messaging.EventHubs 使用 EventProcessorClient 进行检查点
- azure - 具有内部 IP 地址的天蓝色功能或 Web 服务
- java - 我正在尝试制作一个列出平方数的循环。我的 Java 代码有什么问题?
- node.js - Angular 项目没有满足我的要求
- r - 匹配和替换 R 中的行名
- pandas - 在pandas中取消堆叠数据框后的堆叠是不同的
- r - 使用向量中的相关位置来查找索引
- mathematical-optimization - 在混合整数线性规划 (MILP) 中对具有多个条件的 IF-THEN 语句进行建模
- apache-storm - 为什么在这个最小示例中 Trident 不调用 ack() 或 fail()?
- python - 附加 numpy .npy 文件,而无需将它们加载到内存中