我如何让Pandas将包含NaT的列从timedelta转换为datetime?

问题描述 投票:1回答:1

我有一个熊猫数据框,其列的类型为timedelta64[ns],我想将其转换为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',也会发生此错误。供参考,我使用的是熊猫1.0.1

python pandas datetime timedelta
1个回答
0
投票

如果需要将时间增量转换为日期时间,请添加一些开始日期时间:

start = pd.to_datetime('2000-01-01')
df['Animal_death_date'] = pd.to_timedelta(df['Animal_death_date'], errors='coerce') + start

或添加一些由日期时间填充的列:

start = pd.to_datetime(df['FMRIMeasurement_date'])
df['Animal_death_date'] = pd.to_timedelta(df['Animal_death_date'], errors='coerce') + start
© www.soinside.com 2019 - 2024. All rights reserved.