Select Pandas Rows Based on List Index

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

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

Python: Pandas Dataframe select row by given index

Just use .loc:

>>> df.loc['2a']
col1 20.2
col2 30.5
Name: 2a, dtype: float64

>>> df.loc['2a', 'col1']
20.2

Select rows of pandas dataframe from list, in order of list

One way to overcome this is to make the 'A' column an index and use loc on the newly generated pandas.DataFrame. Eventually, the subsampled dataframe's index can be reset.

Here is how:

ret = df.set_index('A').loc[list_of_values].reset_index(inplace=False)

# ret is
# A B
# 0 3 3
# 1 4 5
# 2 6 2

Note that the drawback of this method is that the original indexing has been lost in the process.

More on pandas indexing: What is the point of indexing in pandas?

Use a list of values to select rows from a Pandas dataframe

You can use the isin method:

In [1]: df = pd.DataFrame({'A': [5,6,3,4], 'B': [1,2,3,5]})

In [2]: df
Out[2]:
A B
0 5 1
1 6 2
2 3 3
3 4 5

In [3]: df[df['A'].isin([3, 6])]
Out[3]:
A B
1 6 2
2 3 3

And to get the opposite use ~:

In [4]: df[~df['A'].isin([3, 6])]
Out[4]:
A B
0 5 1
3 4 5

Select rows of pandas dataframe in order of a given list with repetitions and keep the original index

We have to preserve the index by assigning it as a column first so we can set_index after the mering:

list_of_values = [3, 4, 6, 4, 3, 8]
df2 = pd.DataFrame({'A': list_of_values, 'order': range(len(list_of_values))})

dfn = (
df.assign(idx=df.index)
.merge(df2, on='A')
.sort_values('order')
.set_index('idx')
.drop('order', axis=1)
)


     A  B
idx
2 3 3
3 4 5
1 6 2
3 4 5
2 3 3

If you want to get rid of the index name (idx), use rename_axis:

dfn = dfn.rename_axis(None)

A B
2 3 3
3 4 5
1 6 2
3 4 5
2 3 3

select pandas rows by excluding index number

Not sure if that's what you are looking for, posting this as an answer, because it's too long for a comment:

In [31]: d = {'a':[1,2,3,4,5,6], 'b':[1,2,3,4,5,6]}

In [32]: df = pd.DataFrame(d)

In [33]: bad_df = df.index.isin([3,5])

In [34]: df[~bad_df]
Out[34]:
a b
0 1 1
1 2 2
2 3 3
4 5 5

Index rows in Pandas Dataframe not in List of Indexes (Python)

Try this:

data.loc[~ data.index.isin(idx)]

Filter data frame based on index value in Python

try this:

Filter_df  = df[df.index.isin(my_list)]


Related Topics



Leave a reply



Submit