Home > Software design >  How to import data with dates as index from excel with pandas
How to import data with dates as index from excel with pandas

Time:05-15

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

CodePudding user response:

What you are trying to do is to set Date as an index, if I get it right:

df.set_index('Date')

CodePudding user response:

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

CodePudding user response:

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:

Someone with reputation help me with the image :) thanks

  • Related