3

I have a dataset like this:

stock_symbol    stock_date      stock_price_open     stock_price_high   
QRR             8/2/10  2.37    2.42                 2.29
QTM             5/2/10  2.38    2.5                  2.34
QXM             4/2/10  2.57    2.64                 2.39

I read a NYSE dataset: df = pandas.read_csv('NYSE.csv', index_col = 0, parse_dates=True)

When I ran: df[['QRR','QTM','QXM']]

I got this error: KeyError: "['QRR' 'QTM' 'QXM'] not in index"

'QRR', 'QTM', 'QXM' are values of stock_symbol column. Could anyone please show me how to index them?

1 Answer 1

2

You have to use loc:

In [11]: df.loc[['QRR','QTM','QXM']]
Out[11]:
                stock_date  stock_price_open  stock_price_high
stock_symbol
QRR           8/2/10  2.37              2.42              2.29
QTM           5/2/10  2.38              2.50              2.34
QXM           4/2/10  2.57              2.64              2.39

Without loc, df[['QRR','QTM','QXM']], pandas is trying to select those columns (which don't exist, hence the "not in index" message):

In [21]: df[["stock_price_open", "stock_price_high"]]
Out[21]:
              stock_price_open  stock_price_high
stock_symbol
QRR                       2.42              2.29
QTM                       2.50              2.34
QXM                       2.64              2.39

check out the selecting data section of the docs.

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks Andy, I thought when I create a DataFrame from the .csv dataset with this code: df = pandas.read_csv('NYSE.csv', index_col = 0, parse_dates=True) The index_col = 0 would set index for the first column (stock_symbol)
@KiemNguyen ah, yes it does precisely that! ok you just need to use loc :) updated the answer

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.