【问题标题】:How to check and replace date values conditionally in pandas dataframe?如何在熊猫数据框中有条件地检查和替换日期值?
【发布时间】:2018-04-06 17:12:09
【问题描述】:

我正在使用 Python 2.7 和 pandas,并且我有以下数据框:

    col1    col2    col3    date_col
0   123     0       foo     9999-12-31
1   456     1       bar     2017-09-15
2   789     1       psi     9999-12-31  

当我尝试使用此数据框时,我收到以下错误:

pandas._libs.tslibs.OutOfBoundsDattime:越界纳秒时间戳:9999-12-31 00:00:00

我知道这是因为 pandas 可以表示的时间戳窗口有限。

我的问题是:如何将 date_col 列中超出日期窗口边界的所有值替换为默认值(例如 2000-01-01)? 同样在我的真实数据框中,我只知道包含日期的列的索引,所以我不能使用列名。

感谢任何帮助!

【问题讨论】:

    标签: python pandas date dataframe timestamp


    【解决方案1】:

    使用iloc 按位置选择列,使用to_datetime 和参数errors='coerce' 将坏日期替换为NaTs,最后使用fillna 替换为date:

    注意 - 如果像 int 或 str 这样的一些不良数据全部替换为 NaTs。

    date = pd.Timestamp('2000-01-01')
    df.iloc[:, 3] = pd.to_datetime(df.iloc[:, 3], errors='coerce').fillna(date)
    print (df)
       col1  col2 col3   date_col
    0   123     0  foo 2000-01-01
    1   456     1  bar 2017-09-15
    2   789     1  psi 2000-01-01
    

    详情:

    print (df.iloc[:, 3])
    0    9999-12-31
    1    2017-09-15
    2    9999-12-31
    Name: date_col, dtype: object
    
    print (pd.to_datetime(df.iloc[:, 3], errors='coerce'))
    0          NaT
    1   2017-09-15
    2          NaT
    Name: date_col, dtype: datetime64[ns]
    

    另一种解决方案:

    #http://pandas.pydata.org/pandas-docs/stable/timeseries.html#timestamp-limitations
    mask = ~df.iloc[:, 3].str.replace('-','').str[:8].astype(int).between(16770921, 22620411)
    print (mask)
    0     True
    1    False
    2     True
    Name: date_col, dtype: bool
    
    df.iloc[:, 3] = pd.to_datetime(df.iloc[:, 3].mask(mask, '2000-01-01'))
    print (df)
       col1  col2 col3   date_col
    0   123     0  foo 2000-01-01
    1   456     1  bar 2017-09-15
    2   789     1  psi 2000-01-01
    

    【讨论】:

    • 非常感谢!我整个下午都在努力让它工作。这就像一个魅力。接受您的答案作为解决方案。
    【解决方案2】:

    df = df.replace({您要替换的日期的正则表达式}, {date })

    这应该可行

    https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.replace.html

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-01-15
      • 2021-06-19
      • 1970-01-01
      • 2022-08-09
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多