python - 在熊猫数据框中将整数转换为日期时间
问题描述
我曾经
pd.to_numeric (df['dates'], downcast = 'integer')
将 datetime64 转换为 int64 但如果我想将其转换回 datetime 格式,我该怎么办?早些时候它的格式是:2020-02-19,但转换后它现在是 1582070400000000000。我找不到将其恢复为 datetime64 的方法。
解决方案
熊猫 to_datatime 可以解决问题
参见示例:
import pandas as pd
# Example DataFrame
df = pd.DataFrame({'dates' : pd.date_range('01-01-2021','01-10-2021',freq='D')})
# To numeric, as you did
df['numeric'] = pd.to_numeric (df['dates'] , downcast = 'integer')
# Back to date
df['back_do_date'] = pd.to_datetime( df['numeric'] )
给出数据框:df
dates numeric back_do_date
0 2021-01-01 1609459200000000000 2021-01-01
1 2021-01-02 1609545600000000000 2021-01-02
2 2021-01-03 1609632000000000000 2021-01-03
3 2021-01-04 1609718400000000000 2021-01-04
4 2021-01-05 1609804800000000000 2021-01-05
5 2021-01-06 1609891200000000000 2021-01-06
6 2021-01-07 1609977600000000000 2021-01-07
7 2021-01-08 1610064000000000000 2021-01-08
8 2021-01-09 1610150400000000000 2021-01-09
9 2021-01-10 1610236800000000000 2021-01-10
推荐阅读
- javascript - 是否可以通过带有 node/express 的 REST API 返回 javascript 函数?
- r - 使用 read_sav 读取文件 spss 文件后删除额外信息 (attr)
- nvidia-jetson - 在 ubuntu 18 中找不到 Nvidia flash.sh 文件
- angular - Angular 的一次性属性绑定
- java - MVVM with Retrofit - 如何处理存储库中的大量 LiveData?
- google-sheets - 在 Google 表单中只允许一个答案
- python - 如何始终显示 Kivy 滑块值的两个占位符(显示 01 而不是 1)?
- mysql - 在 MYSQL UPDATE、IF 语句或 CASE 语句中哪个更快
- python - 当目标是张量流中的输入之一时如何使用`model.predict`?
- typescript - 如何在 TypeScript 中使用 Cytoscape.Js 扩展?