Search code examples
pythonpython-3.xpandaspandas-datareader

Pandas DataReader produces DataFrame with inaccessible indices


I'm pulling data from pandas.datareader and cannot access the data by index. Here's the code to produce the dataframe with a single, date-indexed row:

import pandas as pd
from pandas_datareader import data
tdata = data.DataReader('SPY', 'iex', '2018-03-23', '2018-03-23')

Now, print(tdata) returns the data as expected:

            open    high     low   close     volume
date                                                 
2018-03-23  264.17  265.02  257.83  258.05  183534751

I can print the index value with print(tdata.index.values), resulting in: ['2018-03-23']

However, print(tdata['2018-03-23']) returns KeyError

Trying to access the index directly through a loop also results in KeyError

for idx in tdata.index.values:
    print(tdata[idx])

Can anyone tell me what I'm missing here?


Solution

  • When referencing as df[id], pandas decides what's inside the [] as follows:

    • String - Gets columns matching the value
    • Int - Gets row with this index, if the index is of int type.
    • Range of index values - Gets a subset of rows with that index

    As you have a non-int type index, try tdata.loc['2018-03-23'] as this will make pandas interpret the string as index value.