【问题标题】:Pandas OutOfBoundsDatetime when cleaning different date formats with dates before 1677Pandas OutOfBoundsDatetime 清除 1677 之前日期的不同日期格式时
【发布时间】:2019-11-25 03:22:50
【问题描述】:

在 Pandas 中,我使用 this answer 来清理各种格式的日期。如果我过滤掉 1677 年之前的日期,这将非常有效。但是我的日期是历史性的,而且很多日期都在 1677 年之前,所以我收到了 OutOfBoundsDatetime 错误。

我的数据包含如下日期:

27 Feb 1928,
1920,
October 2000,
1500,
1625,
Mar 1723

我可以看到reference here 使用 pd.Period 但我不知道如何将它应用到我的案例中,因为需要先清理日期才能调整此示例

我清理日期的代码是:

df['clean_date'] = df.dates.apply(
lambda x: pd.to_datetime(x).strftime('%m/%d/%Y'))

df

我需要帮助来转换和清理我的日期,包括历史日期。感谢您在这方面的帮助。

【问题讨论】:

  • 你的目标是什么?你不能有一个 datetime64[ns] dtype 的 Pandas 系列,其值在 1677-09-21 00:12:43.145225 之前或 2262-04-11 23:47:16.854775807 之后 - 它们将被包装。不过你可以有一个 Period dtype...

标签: python pandas date dataframe datetime


【解决方案1】:

正如online documentation 中明确指出的那样,datetime64[ns] dtype 的值不能落入['1677-09-21 00:12:43.145225', '2262-04-11 23:47:16.854775807']

但是你可以有像 Period dtype 这样的日期。

示例输入数据集:

In [156]: df
Out[156]:
           Date
0   27 Feb 1928
1          1920
2  October 2000
3          1500
4          1625
5      Mar 1723

In [157]: df.dtypes
Out[157]:
Date    object
dtype: object

解决方案:

In [158]: df["new"] = pd.PeriodIndex([pd.Period(d, freq="D") for d in df.Date])

结果:

In [159]: df
Out[159]:
           Date         new
0   27 Feb 1928  1928-02-27
1          1920  1920-01-01
2  October 2000  2000-10-01
3          1500  1500-01-01
4          1625  1625-01-01
5      Mar 1723  1723-03-01

In [160]: df.dtypes
Out[160]:
Date       object
new     period[D]
dtype: object

In [161]: df["new"].dt.year
Out[161]:
0    1928
1    1920
2    2000
3    1500
4    1625
5    1723
Name: new, dtype: int64

【讨论】:

    猜你喜欢
    • 2017-01-17
    • 2019-09-14
    • 1970-01-01
    • 1970-01-01
    • 2012-05-13
    • 1970-01-01
    • 1970-01-01
    • 2015-01-25
    • 1970-01-01
    相关资源
    最近更新 更多