【问题标题】:'DataFrame' object has no attribute 'DatetimeIndex''DataFrame' 对象没有属性 'DatetimeIndex'
【发布时间】:2021-02-20 02:54:23
【问题描述】:

我正在尝试返回一个带有已设置为 DateTimeIndex 的 Date 的 Pandas。我尝试了很多类似的东西

inx=OutputDataSet.DatetimeIndex.to_pydatetime()

inx=OutputDataSet.DatetimeIndex.to_pydatetime(format =''%y-%m-%d'')

但我不断收到错误

'DataFrame' object has no attribute 'DatetimeIndex'

这是 info 属性显示的内容;

<class 'pandas.core.frame.DataFrame'>
DatetimeIndex: 1047 entries, 2017-01-03 to 2021-02-19
Data columns (total 6 columns):
Open         1047 non-null float64
High         1047 non-null float64
Low          1047 non-null float64
Close        1047 non-null float64
Adj Close    1047 non-null float64
Volume       1047 non-null int64
dtypes: float64(5), int64(1)
memory usage: 57.3 KB

很明显有一个DatetimeIndex

打印输出显示DatetimeIndex没有问题

                     Open       High   ...     Adj Close   Volume
Date                               ...                       
2017-01-03   2.870000   2.940000   ...      2.842312   146804
2017-01-04   2.950000   3.090000   ...      2.871415   292371
2017-01-05   3.000000   3.000000   ...      2.871415   186374
2017-01-06   2.950000   2.970000   ...      2.764707   141723
2017-01-09   2.900000   2.970000   ...      2.842312    60815

理想情况下,我希望 DataFrame 呈现为

    Date         1047 non-null datetime
    Open         1047 non-null float64
    High         1047 non-null float64
    Low          1047 non-null float64
    Close        1047 non-null float64
    Adj Close    1047 non-null float64
    Volume       1047 non-null int64

任何帮助将不胜感激

【问题讨论】:

    标签: python pandas dataframe datetimeindex


    【解决方案1】:

    我认为DatetimeIndex 是您在 pandas.DataFrame 上拥有的索引类型。每个DataFrame 都带有属性indexindex 可以是从DateTimeIndexPeriodIndexTimedeltaIndex 的不同类型(guide here

    所以在您的输出中,Date 是您的索引。如果这不是您期望的输出,您可能需要重新考虑使用 pandas DataFrame。

    【讨论】:

    • 我调用的包正在返回 DataFrame,而正在处理数据的目标系统(SQL Server)期望 DataFrame 不会脱离 Pandas。
    • 然后df.index 应该返回您要查找的日期。使用 Pandas 真的很容易,不要误会我的意思。我的意思是,也许阅读文档,看看如何从中得到你想要的。
    • 知道了 - 谢谢 Rikki。 DateTimeIndex 是“属性”索引的“类型”。
    • 没错。因此,您可以将df.index 设置为df['timestamp'] 或调用df.reset_index(inplace=True),这会将您的索引重置为默认值(pandas.pydata.org/pandas-docs/stable/reference/api/…)。当你有机会时,请接受答案。谢谢。
    【解决方案2】:

    解决方法如下;

    OutputDataSet.insert(loc=0,column=''Date'', value=pd.to_datetime(OutputDataSet.index))
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-12-17
      • 2021-07-14
      • 2013-10-23
      • 2017-10-22
      • 2021-01-08
      • 2021-11-01
      • 2016-03-09
      • 2016-04-02
      相关资源
      最近更新 更多