【问题标题】:Change <class 'pandas.core.indexes.base.Index'> to <class 'pandas.core.indexes.datetimes.DatetimeIndex'>将 <class 'pandas.core.indexes.base.Index'> 更改为 <class 'pandas.core.indexes.datetimes.DatetimeIndex'>
【发布时间】:2020-12-02 16:55:44
【问题描述】:

我有

df = pd.read_csv("C:AAPL_MIN.csv", parse_dates=True, index_col='datetime')
print(type(df.index))

如何将类型从 更改为

日期时间为 2020-09-14 09:30:00-04:00

编辑:

这是一个带有输出的更新代码

import pandas as pd    
    
df = pd.read_csv("file",header=0)

df['datetime'] = pd.to_datetime(df['datetime'])

print(type(df['datetime'][0]))
#class 'datetime.datetime'

print(type(df['datetime']))
#class 'pandas.core.series.Series'

df.set_index('datetime', inplace=True, drop=True)

print(type(df.index))
#class 'pandas.core.indexes.base.Index'
                             open     high      low    close   volume
datetime                                                              
2020-10-06 09:30:00-04:00  13.2800  13.3500  13.2300  13.2501  1060985
2020-10-06 09:31:00-04:00  13.2600  13.2600  13.1900  13.2150   377251
2020-10-06 09:32:00-04:00  13.2110  13.2299  13.1922  13.2143   391055

【问题讨论】:

  • 这能回答你的问题吗? python pandas convert index to datetime
  • df.index = pd.to_datetime(df.index) ValueError: Tz-aware datetime.datetime cannot be convert to datetime64 unless utc=True 它不会产生上述错误
  • 这个细节对于包含在初始问题中很重要,作为minimal reproducible example 的一部分。您是否尝试过在错误中设置utc=True
  • 无论我做什么添加utc = True都不能解决问题即使我将列转换为日期时间并将列设置为索引,我也无法将索引作为日期时间
  • 所以上面只是我的csv的一个示例。如果我将我的数据框更改为 df = df[:3] 它可以工作。在我的 22,000 行文件中一定存在数据有效性问题。谢谢你的帮助

标签: python pandas numpy stock


【解决方案1】:

第一个选项

简单替换

df['datetime'] = pd.to_datetime(df['datetime'])

df['datetime'] = pd.DatetimeIndex(df['datetime'])

保持所有其他代码相同。

使用 pd.to_datetime() 格式化列然后将其转换为索引时会出现问题。

第二个选项

如果您想要修改当前索引,而不是再次生成它,另一种选择是:

df.index = pd.DatetimeIndex(df.index)

第三个选项

你也可以一步一步来

  1. 重置索引

df = df.reset_index()

  1. 将列转换为所需的格式

df['datetime'] = pd.DatetimeIndex(df['datetime'])

  1. 将其转换为索引

df.set_index('datetime', inplace = True, drop = True)

我遇到了类似的问题,这解决了。

希望对你有帮助。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-09-13
    • 2020-10-06
    • 2018-01-03
    • 1970-01-01
    • 2013-08-22
    相关资源
    最近更新 更多