首页 > 解决方案 > 在 python 代码中获取属性错误

问题描述

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

AttributeError:“DataFrame”对象没有属性“Date”

如何解决这个问题?

在此处输入图像描述

标签: pythonpandasattributes

解决方案


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

推荐阅读