Skip to content Skip to sidebar Skip to footer

Coercing Date Columns In Pandas With Null Values

I'm reading Excel files and need to properly handle dates when reading them. Oftentimes columns will be sparsely populated with dates, and the rest will be blanks. If I read this,

Solution 1:

You need to coerce it. According to the documentation:

convert_dates : boolean, default True

If True, convert to date where possible. If ‘coerce’, force conversion, with unconvertible values becoming NaT.

The convert_ints flag is False by default, so in this case:

In [51]:
d = {1: {'DateCol': '02/01/2014', 'NotDateCol': 12457}, 2: {'DateCol': np.nan, 'NotDateCol': 45677}}
df = pd.DataFrame.from_dict(d,orient='index').convert_objects(convert_dates='coerce')

In [52]:
df.dtypes

Out[52]:
NotDateCol             int64
DateCol       datetime64[ns]
dtype: object

Post a Comment for "Coercing Date Columns In Pandas With Null Values"