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!
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.
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With