如何在 pandas 数据框中有条件地检查和替换日期值? [英] How to check and replace date values conditionally in pandas dataframe?

查看:96
本文介绍了如何在 pandas 数据框中有条件地检查和替换日期值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am working with Python 2.7 and pandas and I have the following dataframe:

    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  

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

When I try to work with this dataframe I get the following error:


pandas._libs.tslibs.OutOfBoundsDattime:超出范围的纳秒级时间戳:9999-12-31 00:00:00

pandas._libs.tslibs.OutOfBoundsDattime: Out of bounds nanosecond timestamp: 9999-12-31 00:00:00

我知道

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

My question is: How can I replace all the values in the column date_col which are exceeding the bound of the date window with a default value (for example 2000-01-01)? Also in my real dataframe I only know the indices of the columns that contain dates, so I cannot use the column names.

感谢您的帮助!

推荐答案

使用 iloc 以便按位置选择列,其中 to_datetime errors ='coerce'替换不良日期到 NaT s和最后一个 fillna 替换为 date

Use iloc for select column by position with to_datetime with parameter errors='coerce' for replace bad dates to NaTs and last fillna for replace to date:

注意-如果某些错误数据,例如 int str 全部替换为 NaT s。

Notice - If some bad data like int or str all are replaced to 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]






另一个解决方案:


Another solution:

#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

这篇关于如何在 pandas 数据框中有条件地检查和替换日期值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆