8

I have a simple index on my Dataframe (integers from 0:n).

If I want row index values 1,10,100, how do I query the index to get only those rows back?

Thanks

2
  • You can try this way...df.iloc[[1,10,100], :] Commented Feb 16, 2017 at 15:35
  • @su79eu7k I was doing df.loc[df.index.isin([vals])] which seems to work, but I didn't know if that was a good way of doing it. Commented Feb 16, 2017 at 15:37

3 Answers 3

8

In your case, the index equals to integer position. Thus you can use either .loc or .iloc.

.loc is primarily label based...

.iloc is primarily integer position based (from 0 to length-1 of the axis)

See different-choices-for-indexing

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

Comments

6

Try this:

result = data.loc[[1,10,100]]

1 Comment

Calvin is there a difference between using iloc vs loc?
1

If someone prefers to perform query for any reason, it can be done like this:

df.query("index in [1,10,100]")

From documentation of pandas.DataFrame.query:

The DataFrame.index and DataFrame.columns attributes of the DataFrame instance are placed in the query namespace by default, which allows you to treat both the index and columns of the frame as a column in the frame. The identifier index is used for the frame index; you can also use the name of the index to identify it in a query.

Comments

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.