Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to maintain order when selecting rows in pandas dataframe?

Tags:

python

pandas

I want to select rows in a particular order given in a list. For example

This dataframe

a=[['car',1],['bike',3],['jewel',2],['tv',5],['phone',6]]

df=pd.DataFrame(a,columns=['items','quantity'])

>>> df
   items  quantity
0    car         1
1   bike         3
2  jewel         2
3     tv         5
4  phone         6

I want to get the rows with this order ['tv','car','phone'], that is, first row tv and then car and then phone. I tried this method but it doesn't maintain order

arr=['tv','car','phone']

df.loc[df['items'].isin(arr)]

   items  quantity
0    car         1
3     tv         5
4  phone         6
like image 256
Eka Avatar asked Jun 19 '19 00:06

Eka


People also ask

Does pandas DataFrame preserve row order?

Answer. Yes, by default, concatenating dataframes will preserve their row order.

How do I order rows in pandas?

You can sort by column values in pandas DataFrame using sort_values() method. To specify the order, you have to use ascending boolean property; False for descending and True for ascending. By default, it is set to True.

How do you select first 10 rows in pandas?

You can use df. head() to get the first N rows in Pandas DataFrame. Alternatively, you can specify a negative number within the brackets to get all the rows, excluding the last N rows.


1 Answers

Here's a non-intrusive solution using Index.get_indexer that doesn't involve setting the index:

df.iloc[pd.Index(df['items']).get_indexer(['tv','car','phone'])]

   items  quantity
3     tv         5
0    car         1
4  phone         6

Note that if this is going to become a frequent thing (by thing, I mean "indexing" with a list on a column), you're better off turning that column into an index. Bonus points if you sort it.

df2 = df.set_index('items')
df2.loc[['tv','car','phone']]  

       quantity
items          
tv            5
car           1
phone         6
like image 172
cs95 Avatar answered Sep 28 '22 05:09

cs95