pythonpandasdataframesubsetyfinance

dataframe how to get subset of rows in a dataframe


I have the following code:

import yfinance as yf
stocks1 = ['AAL','AAPL','ABBV']
new_df1 = yf.download(tickers=stocks1,
                     start='2023-10-01',
                     end='2023-10-10')
new_df1

It generates a dataframe, a pic of which I have included below:

dataframe

I would like to get a subset of this dataframe containing only the column Adj Close for both stocks and between dates 2023-10-03 and 2023-10-06.


Solution

  • yf.download creates a new dataframe with an index on date. You can use df.loc (documentation) to select values of Adj Close between two dates:

    new_df1.loc['2023-10-03':'2023-10-06', 'Adj Close']
    
                  AAL        AAPL        ABBV
    Date                                     
    2023-10-03  12.29  171.953735  143.249680
    2023-10-04  12.73  173.210495  143.502304
    2023-10-05  12.85  174.457260  143.269119
    2023-10-06  12.76  177.030579  144.036728