【发布时间】:2020-09-05 09:17:11
【问题描述】:
我有一个带有 timedelta64[ns] 类型列的 pandas 数据框,我想将其转换为 datetime64[ns]。
pd.to_datetime() 函数声称可以做到这一点,并且过去有效,但现在似乎失败了。我认为这可能与我没有注意到的 API 怪癖有关。目前它失败了:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/lib/python3.7/site-packages/pandas/core/tools/datetimes.py", line 724, in to_datetime
cache_array = _maybe_cache(arg, format, cache, convert_listlike)
File "/usr/lib/python3.7/site-packages/pandas/core/tools/datetimes.py", line 152, in _maybe_cache
cache_dates = convert_listlike(unique_dates, format)
File "/usr/lib/python3.7/site-packages/pandas/core/tools/datetimes.py", line 363, in _convert_listlike_datetimes
arg, _ = maybe_convert_dtype(arg, copy=False)
File "/usr/lib/python3.7/site-packages/pandas/core/arrays/datetimes.py", line 1916, in maybe_convert_dtype
raise TypeError(f"dtype {data.dtype} cannot be converted to datetime64[ns]")
TypeError: dtype timedelta64[ns] cannot be converted to datetime64[ns]
要尝试复制,请使用下面的 MWE:
wget https://chymera.eu/ppb/61ebad.csv
python
import pandas as pd
df = pd.read_csv('61ebad.csv')
df['Animal_death_date'] = pd.to_timedelta(df['Animal_death_date'], errors='coerce')
df['Animal_death_date'] = pd.to_datetime(df['Animal_death_date'], errors='coerce')
如果我使用errors='ignore',也会出现该错误。
作为参考,我使用的是 Pandas 1.0.1。
【问题讨论】:
-
不确定这里的逻辑是什么,您需要如何将 timedelta 转换为 datetime?添加一些由日期时间填充的列?或者添加一些标量,例如
df['Animal_death_date'] = pd.to_timedelta(df['Animal_death_date'], errors='coerce') + pd.to_datetime('2000-01-01')?
标签: python pandas datetime timedelta