【问题标题】:How to convert object to datetime Index [duplicate]如何将对象转换为日期时间索引 [重复]
【发布时间】:2018-11-27 01:49:07
【问题描述】:

我有带有列 date 的数据框。 Date 列的值类似于 Index([2011-01-10], dtype='object')。我想转换为 DateTime 但我无法做到这一点。我试过df["Date"] = pd.to_datetime(df["Date"]),但没有用。收到错误TypeError: <class 'pandas.core.indexes.base.Index'> is not convertible to datetime。谁能帮我解决这个问题?

【问题讨论】:

  • 我怀疑您将长度为 1 的索引作为 'Date' 列中的值。这就是我们所说的……搞砸了!试试这个df.Date = pd.to_datetime(df.Date.str[0])
  • 尝试使用 df['dateindex'] = df.index 将日期索引传递给列,然后转换为日期时间。或者更好的是@Vaishali 提到,直接使用 df.index 进行转换。
  • 等等,这很奇怪。 COLUMN 日期是索引?
  • 由于日期是索引,使用 df.index = pd.to_datetime(df.index)
  • OP,如果 dup 目标满足您的需求,请说出来。否则,我可以重新提出问题。

标签: python pandas datetime


【解决方案1】:

设置

df = pd.DataFrame(dict(Date=[pd.Index(['2018-01-01'])] * 2))

df

                                    Date
0  Index(['2018-01-01'], dtype='object')
1  Index(['2018-01-01'], dtype='object')

错误

df.Date = pd.to_datetime(df.Date)    

TypeError: <class 'pandas.core.indexes.base.Index'> is not convertible to datetime

解决方案

df.Date = pd.to_datetime(df.Date.str[0])

df

        Date
0 2018-01-01
1 2018-01-01

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-12-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-06-02
    • 2018-03-03
    • 1970-01-01
    • 2021-01-14
    相关资源
    最近更新 更多