【问题标题】:Handle Perpetual Maturity Bonds with Maturity date of 31-12-9999 12:00:00 AM办理到期日为 31-12-9999 12:00:00 AM 的永续债
【发布时间】:2018-03-22 06:02:39
【问题描述】:

我在到期日期的数据框中有许多记录 列是 31-12-9999 12:00:00 AM,因为债券永远不会到期。这 自然会引发错误:

Out of bounds nanosecond timestamp: 9999-12-31 00:00:00

我看到最大日期是:

pd.Timestamp.max
Timestamp('2262-04-11 23:47:16.854775807')

我只是想澄清清除 datframe 中所有日期列并修复我的错误的最佳方法是什么?我的代码模仿了文档:

df_Fix_Date = df_Date['maturity_date'].head(8)
display(df_Fix_Date)
display(df_Fix_Date.dtypes)

0    2020-08-15 00:00:00.000
1    2022-11-06 00:00:00.000
2    2019-03-15 00:00:00.000
3    2025-01-15 00:00:00.000
4    2035-05-29 00:00:00.000
5    2027-06-01 00:00:00.000
6    2021-04-01 00:00:00.000
7    2022-04-03 00:00:00.000
Name: maturity_date, dtype: object

def conv(x):
        return pd.Period(day = x%100, month = x//100 % 100, year = x // 10000, freq='D')

df_Fix_Date['maturity_date'] = pd.to_datetime(df_Fix_Date['maturity_date'])               # convert to datetype
df_Fix_Date['maturity_date'] = pd.PeriodIndex(df_Fix_Date['maturity_date'].apply(conv))   # fix error
display(df_Fix_Date)

输出:

KeyError: 'maturity_date'

【问题讨论】:

    标签: pandas date dataframe string-to-datetime


    【解决方案1】:

    存在无法转换为越界日期时间的问题。

    一种解决方案是将9999 替换为2261

    df_Fix_Date['maturity_date'] = df_Fix_Date['maturity_date'].replace('^9999','2261',regex=True)
    df_Fix_Date['maturity_date'] = pd.to_datetime(df_Fix_Date['maturity_date']) 
    print (df_Fix_Date)
      maturity_date
    0    2020-08-15
    1    2022-11-06
    2    2019-03-15
    3    2025-01-15
    4    2035-05-29
    5    2027-06-01
    6    2021-04-01
    7    2261-04-03
    

    另一种解决方案是将所有日期替换为更高的年份,如 22612261

    m = df_Fix_Date['maturity_date'].str[:4].astype(int) > 2261
    df_Fix_Date['maturity_date'] = df_Fix_Date['maturity_date'].mask(m, '2261' + df_Fix_Date['maturity_date'].str[4:])
    df_Fix_Date['maturity_date'] = pd.to_datetime(df_Fix_Date['maturity_date']) 
    print (df_Fix_Date)
      maturity_date
    0    2020-08-15
    1    2022-11-06
    2    2019-03-15
    3    2025-01-15
    4    2035-05-29
    5    2027-06-01
    6    2021-04-01
    7    2261-04-03
    

    或者通过参数errors='coerce'将有问题的日期替换为NaTs:

    df_Fix_Date['maturity_date'] = pd.to_datetime(df_Fix_Date['maturity_date'], errors='coerce') 
    print (df_Fix_Date)
      maturity_date
    0    2020-08-15
    1    2022-11-06
    2    2019-03-15
    3    2025-01-15
    4    2035-05-29
    5    2027-06-01
    6    2021-04-01
    7           NaT
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-11-11
      • 2012-06-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多