python - 清理 1677 年之前日期的不同日期格式时的 Pandas OutOfBoundsDatetime

标签 python pandas date dataframe datetime

对于 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

我需要帮助来转换和清理我的日期,包括历史日期。感谢您对此的帮助。

最佳答案

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

但是您可以使用“Period”类型这样的日期。

示例输入数据集:

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

关于python - 清理 1677 年之前日期的不同日期格式时的 Pandas OutOfBoundsDatetime,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57056424/

相关文章:

javascript - 日期时间转换为日期字符串 - javascript

python - 使用正则表达式提取代码(不规则的正则表达式键)

c++ - 从 Python 调用 C/C++?

python - 如何在Python中实现流水线?

python - 匹配任何语言的字母

python-3.x - pandas 使用 series.values 获取 numpy ndarray

python-3.x - 继承和 Pandas

Java:JPQL 日期函数将时间段添加到另一个日期

mysql - 在 MySql 中查找特定日期

Python scipy find_simplex 卡住