8

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!

frank
  • 3,036
  • 7
  • 33
  • 65
  • 1
    `df.loc[list_]` also dont name a variable as `list` since it is a builtin function – anky Aug 28 '19 at 11:09

1 Answers1

18

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
James Wright
  • 1,293
  • 2
  • 16
  • 32
jezrael
  • 822,522
  • 95
  • 1,334
  • 1,252