将包含 1600 年之前日期的字符串转换为 Pandas 中的日期时间对象

问题描述

我正在处理中世纪羊皮纸的数据集。尝试在 Pandas DateTime 对象中转换这种格式的日期 '1140 01 12' '%Y %m %d' 。不幸的是,pandas 只能以 ns 分辨率处理大约 1660 年前的日期。我可以接受一天的决议,但我无法让它发挥作用:

import pandas as pd 
d = {'date': ['1140 01 12','1140 02 16','1140 04 12','1200 10 27'],'col2': [3,4,5,6]}
pd.to_datetime(d['date'],format='%Y %m %d',origin = "julian",unit = "D")

我有ValueError: incompatible 'arg' type for given 'origin'='julian'知道如何解决这个问题吗?

解决方法

你可以试试pd.Period

def conv(x):
    year,day,month = map(int,x.split(" "))
    return pd.Period(year=year,month=month,day=day,freq="D")


d = {"date": ["1140 01 12","1140 02 16","1140 04 12"],"col2": [3,4,5]}
df = pd.DataFrame(d)

df["date"] = df["date"].apply(conv)
print(df)

打印:

         date  col2
0  1140-12-01     3
1  1147-03-18     4
2  1140-12-04     5