熊猫无法识别旧日期(1600 年之前)

时间:2021-04-10 14:41:30

标签: python python-3.x pandas datetime

我以 csv 格式输入数据。大多数日期在 1900 年之后,但有些比这更早。迄今为止我见过的最古老的是 1518 年。

1518 日期实际上出现了越界错误。我知道 python 应该能够处理高达 584 岁左右的日期,但在这种情况下却没有。这个限制不是问题。

这是我的数据示例:

Index,Dates
00457,01/01/1981
134535,22/12/1977
3015,15/11/1889
00458,01/01/1981
00459,01/01/1981
134774,10/01/1978
00461,01/01/1981
00764,01/01/2000
00462,01/01/1981
00899,23/09/1518
00063,01/01/1981
00464,01/01/1981

在使用中读取文件后:

DF = pd.read_csv(sourceFile5,parse_dates=['Dates'], dayfirst=True, index_col="cNumber", skipinitialspace = True)

格式很好,但是当我尝试使用

过滤结果时
newDF.append(DF[ DF["Dates"] > one_month_ago])

(请注意 one_month_ago 是我的脚本定义的变量)

没有任何条目被识别(即使是 1900 年以后的条目)。我知道过滤器命令有效,因为我已经将它们与不包含此类旧日期的其他 .csv 文件一起使用,并且没有出现任何问题。

出于这个原因,我添加了额外的步骤:

DF["Dates"] = pd.to_datetime(DF["Dates"], dayfirst = True, format = "%d/%m/%Y", errors = "coerce")

1900 年后的日期返回正常,但更早的日期返回为 YYYY-MM-DD。即便如此,即使在这个额外的步骤之后,在我上面提到的过滤阶段也不会被识别出来。该列似乎以一系列字符串的形式返回。

我不知道为什么会这样。有人可以帮忙吗?

1 个答案:

答案 0 :(得分:0)

根据 documentation, there's limitation可以使用 64 位整数表示的时间跨度被限制为大约 584 年)。

您可以represent Out-of-Bounds Spans使用 Periods 进行计算:

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


df = pd.read_csv("your_file.csv")
df["Dates"] = df["Dates"].apply(conv)
print(df["Dates"])

打印:

0     1981-01-01
1     1977-12-22
2     1889-11-15
3     1981-01-01
4     1981-01-01
5     1978-01-10
6     1981-01-01
7     2000-01-01
8     1981-01-01
9     1518-09-23
10    1981-01-01
11    1981-01-01
Name: Dates, dtype: period[D]

编辑:去掉1518-09-23后,就可以正常加载文件了:

df = pd.read_csv("your_file.csv")
df["Dates"] = pd.to_datetime(df["Dates"])
print(df["Dates"])

打印:

0    1981-01-01
1    1977-12-22
2    1889-11-15
3    1981-01-01
4    1981-01-01
5    1978-10-01
6    1981-01-01
7    2000-01-01
8    1981-01-01
9    1981-01-01
10   1981-01-01
Name: Dates, dtype: datetime64[ns]

注意 datetime64[ns]