将系列转换为 Pandas DateTime [英] Converting Series to Pandas DateTime

查看:52
本文介绍了将系列转换为 Pandas DateTime的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

D = ["10Aug49","21Jan45","15Sep47","13Jun52"],将其转换为熊猫日期,确保年份是 1900 年而不是 2000 年.到目前为止,我有这个代码可以转换和打印熊猫日期但世纪是 2000 年,我想要 1900 年.

D = ["10Aug49","21Jan45","15Sep47","13Jun52"], convert this into pandas date, make sure that year is 1900 not 2000. So far i have this code which converts and prints the pandas date but century is 2000, i want 1900.

import pandas as pd

from datetime import datetime

Dae = pd.Series(["10Aug49","21Jan45","15Sep47","13Jun52"])
x =[]

for i in Dae:
    x = datetime.strptime(i,"%d%b%y")
    print(x)

推荐答案

我觉得最好先修正年份,然后转换为日期时间:

I feel better to correct the year first, then convert to datetime:

# identify the year as the last group of digits and prepend 19
corrected_dates = Dae.str.replace('(\d+)$',r'19\1')

# convert to datetime
pd.to_datetime(corrected_dates)

输出:

0   1949-08-10
1   1945-01-21
2   1947-09-15
3   1952-06-13
dtype: datetime64[ns]

这篇关于将系列转换为 Pandas DateTime的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆