带有熊猫的Datetime的字符串:TypeError:<class'list'=“”>无法转换为datetime

时间:2019-02-12 15:58:32

标签: python pandas datetime

我有一个熊猫数据框,其日期列具有以下结构:

352    [2012-01-12 05:04:58]
353    [2008-07-16 20:38:21]
354    [2009-05-12 01:05:48]
355    [2012-01-12 05:04:58]
356    [2018-01-05 15:06:41]
357    [2017-07-17 22:03:43]

Name: Date, Length: 358, dtype: object

如您所见,这些是带有的“对象”。我想将它们转换为Datetime对象。因此,我使用了pandas函数:

pd.to_datetime(df['Date'])

哪个给了我以下错误:

Traceback (most recent call last):
  File "/anaconda3/envs/py35thesis/lib/python3.5/site-packages/IPython/core/interactiveshell.py", line 3267, in run_code
    exec(code_obj, self.user_global_ns, self.user_ns)
  File "<ipython-input-185-adf5e63a666b>", line 1, in <module>
    pd.to_datetime(df['Date'])
  File "/anaconda3/envs/py35thesis/lib/python3.5/site-packages/pandas/core/tools/datetimes.py", line 451, in to_datetime
    values = _convert_listlike(arg._values, True, format)
  File "/anaconda3/envs/py35thesis/lib/python3.5/site-packages/pandas/core/tools/datetimes.py", line 368, in _convert_listlike
    require_iso8601=require_iso8601
  File "pandas/_libs/tslib.pyx", line 492, in pandas._libs.tslib.array_to_datetime
  File "pandas/_libs/tslib.pyx", line 744, in pandas._libs.tslib.array_to_datetime
  File "pandas/_libs/tslib.pyx", line 677, in pandas._libs.tslib.array_to_datetime
TypeError: <class 'list'> is not convertible to datetime

1 个答案:

答案 0 :(得分:2)

让我们说您的列名是日期,您可以使用Apply

df['date'] = df['date'].apply(lambda x: pd.to_datetime(x[0]))

    date
352 2012-01-12 05:04:58
353 2008-07-16 20:38:21