When I have a dataframe
df = DataFrame({'A': [5, 6, 3, 4], 'B': [1, 2, 3, 5]})
df
A B
0 5 1
1 6 2
2 3 3
3 4 5
I can use
df[df['A'].isin([3, 6])]
in order to select rows having the passed values.
Is there also a way to keep the order of the input list?
So that my output is not:
A B
1 6 2
2 3 3
but
A B
1 3 3
2 6 2
2 Answers. Show activity on this post. The order of elements in a pandas Series (i.e., a column in a pandas DataFrame) will not change unless you do something that makes it change.
Pandas DataFrame isin() Method The isin() method checks if the Dataframe contains the specified value(s). It returns a DataFrame similar to the original DataFrame, but the original values have been replaced with True if the value was one of the specified values, otherwise False .
In order to sort the data frame in pandas, function sort_values() is used. Pandas sort_values() can sort the data frame in Ascending or Descending order.
Reorder Columns using Pandas . Another way to reorder columns is to use the Pandas . reindex() method. This allows you to pass in the columns= parameter to pass in the order of columns that you want to use.
This is a bit long, but it works. isin(), then sort_values() based on the list.
df = pandas.DataFrame({'A' : [5,6,3,4], 'B' : [1,2,3,5]})
mylist = [3,6]
ndf = df[df['A'].isin(mylist)]
ndf['sort_cat'] = pandas.Categorical(ndf['A'], categories=mylist, ordered=True)
ndf.sort_values('sort_cat', inplace=True)
ndf.reset_index(inplace=True)
print ndf
A B sort_cat
2 3 3 3
1 6 2 6
(I based this answer on sort pandas dataframe based on list)
Another option which filters and sorts in one shot
import pandas as pd
from functools import reduce
reduce(pd.DataFrame.append, map(lambda i: df[df.A == i], [3, 6]))
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