10

Similar to Select multiple sections of rows by index in pandas, I have large dataframe, and there are a few indexes I am interested in viewing.

I have:

import pandas as pd 
df = pd.DataFrame({'A':[0,1,2,3,4,5,6,7,8,9],'B':['a','b','c','d','e','f','g','h','i','j']},
                  index=range(10,20,))

and there are few indexes I want to see, list=[12,15,10,14]

so that I end up with:

    A  B
12  2  c
15  5  f
10  0  a
14  4  e

is there a command so that I can go:

df.iloc[[index isin list]]

as the value list is made from an earlier piece of code.

I tried:

df.loc[[ix]]

where ix=dm.iloc[250].sort_values()[:10].index and is Int64Index([250, 1109, 427, 513, 678, 18, 697, 1075, 533, 739], dtype='int64')

to no avail.

suggestions welcomed!

1
  • 1
    df.loc[list_] also dont name a variable as list since it is a builtin function Commented Aug 28, 2019 at 11:09

1 Answer 1

21

First change list to another name like L, because list is a reserved word in Python. Then select by DataFrame.loc for selecting by labels:

L=[12,15,10,14]
df = df.loc[L]
print (df)
    A  B
12  2  c
15  5  f
10  0  a
14  4  e

Your solution is close for select by positions with DataFrame.iloc function:

L1 = [2,5]
df = df.iloc[L1]

print (df)
    A  B
12  2  c
15  5  f
Sign up to request clarification or add additional context in comments.

6 Comments

How do I select multiple slices, or ranges, of rows? For example first two rows together with the last row
@Nermin - Do you think L1 = [0,1,-1] ?
I was thinking of something more like L1 = [a:b, c:d]. Where a < b < c < d. Is such a thing possible?
@Nermin - Do you think this ?
Yes, thank you. But just curious, is there no native or pandas solution available, rather than using Numpy?
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.