Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pandas 'isin' with output keeping order of input list

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
like image 785
Nikita Avatar asked May 01 '14 18:05

Nikita


People also ask

Does pandas Tolist preserve order?

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.

What does the ISIN () function do in pandas?

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 .

How do I rearrange data in pandas?

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.

How do I rearrange the order of columns in pandas?

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.


2 Answers

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)

like image 131
J. Rigby Avatar answered Oct 05 '22 04:10

J. Rigby


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]))
like image 31
javigzz Avatar answered Oct 05 '22 02:10

javigzz