【问题标题】:Getting an attribute error in python code在 python 代码中获取属性错误
【发布时间】:2020-07-28 17:36:27
【问题描述】:

如何将日期列设置为索引?我收到一个错误

AttributeError: 'DataFrame' 对象没有属性 'Date'

如何解决这个问题?

【问题讨论】:

  • 好像已经是索引了。这也可以解释AttributeError。我只是猜测,但如果你在 Jupyter 中将你的单元格移动到执行的单元格周围,这可能会发生这种情况。
  • 您能否提供您如何读取数据的代码?如果你在pd.read_excel中读取了带有参数set_index('Date')的文件,你会在尝试调用df['Date']时得到AttributeError
  • df = web.DataReader('^BSESN', data_source = 'yahoo', start = '2015-07-16', end = '2020-07-16')

标签: python pandas attributes


【解决方案1】:

Date 列已经是索引列,不是吗? 如果您想尝试,您可以重置索引列并再次设置它。 你会得到同样的结果。

但是,如果你想修改你的 Date 列,你可以通过重置索引列,修改它,然后将它设置回索引来实现。

import pandas as pd
import pandas_datareader as web

df = web.DataReader('^BSESN', data_source='yahoo', start='2015-07-16', end='2020-07-16')
df.reset_index(level=0, inplace=True)

# If you want to modify your index column, you can do it here.
df['Date'] = pd.to_datetime(df.Date, format='%Y-%m-%d')

df.index = df['Date']
df.drop('Date', axis=1, inplace=True)
df

【讨论】:

    【解决方案2】:

    看起来您已经将Date 作为索引。

    要将任意列设置为索引,也可以尝试:

    df = df.set_index('Date')
    

    这会将您的 Date 列设置为索引,并将您当前的索引保存到 DataFrame 中,并且还将确保 DataFrame 中不存在 Date 的副本。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-05-23
      • 2014-05-30
      • 1970-01-01
      • 1970-01-01
      • 2022-08-18
      • 2022-07-02
      相关资源
      最近更新 更多