简体   繁体   中英

How to import data with dates as index from excel with pandas

I am importing the data with this command

df = pd.read_excel('C:/Users/Me/Data.xlsx', sheet_name='Prices')

and this is the result:

1

The date is a common column and I want it like this:

2

I found the answer.Adding parse_dates=True , index_col=0 to the import command like this:

df = pd.read_excel('C:/Users/Me/Data.xlsx', sheet_name='Prices', parse_dates=True, index_col=0)

The output is this:

1

如果我做对了,您要做的是将 Date 设置为索引:

df.set_index('Date')

I found a better way to import them, because when I was trying to calculate the monthly returns it does not work. So I use this new code and the date were perfect.

df = pd.read_excel('C:/Users/Me/Data.xlsx', sheet_name='Prices')
df.index = pd.to_datetime(df['Date'])
df.drop(['Date'], axis = 'columns', inplace=True)
df.head()

and this is the result:

1

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM