Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

select multiple rows by index in pandas if it is in a list

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!

like image 728
frank Avatar asked Aug 28 '19 11:08

frank


People also ask

How do you select rows of pandas DataFrame based on values in a list?

isin() to Select Rows From List of Values. DataFrame. isin() method is used to filter/select rows from a list of values. You can have the list of values in variable and use it on isin() or use it directly.

How do you select rows based on index list?

You can select rows from a list index using index. isin() Method which is used to check each element in the DataFrame is contained in values or not.

How do I select specific rows in pandas based on index?

Use pandas DataFrame. iloc[] & DataFrame. loc[] to select rows by integer Index and by row indices respectively. iloc[] operator can accept single index, multiple indexes from the list, indexes by a range, and many more.


1 Answers

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
like image 101
jezrael Avatar answered Sep 24 '22 04:09

jezrael