1

I use API to get the stock from Yahoo; however, the first column is ['Date'], I need index column- to further Date vs interested parameter.

I tried to add an index column but it seems not working.

import yfinance as yf
import datetime
stocks = ["MU"]
start = datetime.datetime(2016,10,1)
end = datetime.datetime(2019,10,1) 
data = yf.download(stocks, start=start, end=end)
------------------------------------------------
#Use pandas to make data frame
df = pd.DataFrame(data)
------------------------------------------------
The data frame like this:
             Open   High    Low  Close  Adj Close    Volume
Date                                                       
2016-10-03  17.99  18.02  17.60  17.73      17.73  26856100
2016-10-04  17.98  18.04  17.66  17.80      17.80  54502800
2016-10-05  17.55  18.33  17.28  17.70      17.70  67739500
2016-10-06  17.64  17.89  17.54  17.73      17.73  21606800
2016-10-07  17.72  17.80  17.30  17.61      17.61  23849000
df.index=pd.to_datetime(df.index)

df['Open']

Date
2016-10-03    17.99
2016-10-04    17.98
2016-10-05    17.55
2016-10-06    17.64
2016-10-07    17.72
          ...  
2019-09-25    48.47
2019-09-26    49.38
2019-09-27    45.90
2019-09-30    43.00
2019-10-01    43.10
3
  • 2
    df.reset_index(drop=True) to convert an index into a column. Commented Oct 13, 2019 at 23:38
  • I don't understand the problem, when I run the code there is already a DateTimeIndex, why do you want to use pd.to_datetime? Commented Oct 13, 2019 at 23:39
  • True.... my bad. Commented Oct 14, 2019 at 0:05

1 Answer 1

1

Date is the name of the index, not a column. Try the following:

df.index=pd.to_datetime(df.index)
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.