python - pandas to_datetime 无法按预期工作

标签 python pandas

我有一个 df,其条目主要是 'yyyymmdd' 日期字符串,但也有一些 'nan' 值。请注意,这里这些'nan'字符串而不是浮点nan。现在我想将 df 中的所有日期字符串转换为 pandas 日期时间格式,同时将 nan 值转换为 NaNNaT 等,无论什么可以通过pd.isnull检测到。

立即想到的是将 pd.to_datetime 函数与 errors 参数一起使用。正如文档中所述,

errors : {'ignore', 'raise', 'coerce'}, default 'raise'
- If 'raise', then invalid parsing will raise an exception
- If 'coerce', then invalid parsing will be set as NaT
- If 'ignore', then invalid parsing will return the input

所以,我尝试使用我的示例df

            001002.XY 600123.AB 123456.YZ 555555.GO
ipo_date     20100203  20150605       nan  20090501
delist_date       nan  20170801       nan       nan

其中所有值都是str,甚至nan实际上都是'nan'。然后我尝试了 pd.to_datetime(df,errors='coerce'),这引发了我:

Traceback (most recent call last):
  File "D:\Anaconda3\lib\site-packages\IPython\core\interactiveshell.py", line 2881, in run_code
    exec(code_obj, self.user_global_ns, self.user_ns)
  File "<ipython-input-27-43c41318d6ab>", line 1, in <module>
    pd.to_datetime(df, errors='coerce')
  File "D:\Anaconda3\lib\site-packages\pandas\core\tools\datetimes.py", line 512, in to_datetime
    result = _assemble_from_unit_mappings(arg, errors=errors)
  File "D:\Anaconda3\lib\site-packages\pandas\core\tools\datetimes.py", line 591, in _assemble_from_unit_mappings
    "[{0}] is missing".format(','.join(req)))
ValueError: to assemble mappings requires at least that [year, month, day] be specified: [day,month,year] is missing

但是,如果我尝试使用单个单元格,效果很好:

pd.to_datetime(df.iloc[0, 0])
Out[33]: 
Timestamp('2010-02-03 00:00:00')
pd.to_datetime(df.iloc[1, 0])
Out[34]: 
NaT

我不明白发生了什么。无论如何,所有列都有 object 作为 dtype:

df.dtypes
Out[35]: 
001002.XY    object
600123.AB    object
123456.YZ    object
555555.GO    object
dtype: object

但这似乎不是罪魁祸首:我也用单独的列进行了测试,结果很好:

pd.to_datetime(df.iloc[:, 0])
Out[36]: 
ipo_date      2010-02-03
delist_date          NaT
Name: 001002.XY, dtype: datetime64[ns]

有人可以帮忙或解释一下吗?谢谢!

最佳答案

做法应该略有不同 - 将 pd.to_datetime 应用于所有列:

In [6]: df.apply(pd.to_datetime, errors='coerce')
Out[6]:
             001002.XY  600123.AB 123456.YZ  555555.GO
ipo_date    2010-02-03 2015-06-05       NaT 2009-05-01
delist_date        NaT 2017-08-01       NaT        NaT

如果将 DataFrame 传递给 pd.to_datetime() - 它需要像(年、月、日和可选的:小时、分钟、秒)这样的列,以便组合来自不同列的日期时间.

来自docs:

Assembling a datetime from multiple columns of a DataFrame. The keys can be common abbreviations like [year, month, day, minute, second, ms, us, ns]) or plurals of the same

关于python - pandas to_datetime 无法按预期工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47236658/

相关文章:

pandas - 在 Pandas 中将多个类别合二为一

python - 如何连续生成一个范围内的值?

python - pandas dataframe python列中词频计数的输出不一致

python - matplotlib SpanSelector 小部件 : how to use inside a function?

python - `nth` 破坏了 pandas 中排序的数据框

Python:连续检查添加到列表的文件的大小,在大小处停止,zip列表,继续

python - 从 nginx 中删除不需要的前导斜杠

python - 计算两个数据帧之间的半正矢距离

python - 使用 numpy.einsum 转置时间矩阵 : x^T * x

python - 阻止Python定义的执行