用空值强制Pandas中的日期列

2024-06-17 13:45:57 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在阅读Excel文件,需要在读取时正确处理日期。通常情况下,列中会稀疏地填充日期,其余的将是空白。如果我读这个,它总是作为object数据类型来读取。我想正确地将它们改为datetime64[ns],同时不要错误地转换实际的数值列。在

d = {1: {'DateCol': '02/01/2014', 'NotDateCol': 12457}, 2: {'DateCol': np.nan, 'NotDateCol': 45677}}
df = pd.DataFrame.from_dict(d,orient='index')
In [96]: df.dtypes
Out[96]: 
NotDateCol     int64
DateCol       object
dtype: object

如果你看这个,你可以清楚地看到DateCol是一个日期:

^{pr2}$

现在我需要一些智能的方法来将日期列转换为日期,而不需要事先知道标题名称或类型

尝试只使用to_datetime将整数强制为日期,如下所示:

In [97]: for col in df.columns:
    df[col]  = pd.to_datetime(df[col])
   ....:     

In [98]: df
Out[98]: 
                     NotDateCol    DateCol
1 1970-01-01 00:00:00.000012457 2014-02-01
2 1970-01-01 00:00:00.000045677        NaT

In [99]: df.dtypes
Out[99]: 
NotDateCol    datetime64[ns]
DateCol       datetime64[ns]
dtype: object

有没有什么明智的方法可以让它正常工作,它可以正确地选择日期时间类的列并将其转换,而不是将数字转换为1970-01-01?在


Tags: to方法indfdatetimeobjectcolout
1条回答
网友
1楼 · 发布于 2024-06-17 13:45:57

你需要强迫它。根据documentation

convert_dates : boolean, default True

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

默认情况下,convert_ints标志为False,因此在本例中:

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

相关问题 更多 >