Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rearrange rows of pandas dataframe based on list and keeping the order

Tags:

pandas

numpy

import numpy as np 
import pandas as pd

df = pd.DataFrame(data={'result':[-6.77,6.11,5.67,-7.679,-0.0930,4.342]}\
,index=['A','B','C','D','E','F'])
new_order = np.array([1,2,2,0,1,0])

The new_order numpy array assigns each row to one of three groups [0,1 or 2]. I would like to rearrange the rows of df so that those rows in group 0 appear first, followed by 1, and finally 2. Within each of the three groups the initial ordering should remain unchanged.

At the start the df is arranged as follows:

   result
A  -6.770
B   6.110
C   5.670
D  -7.679
E  -0.093
F   4.342

Here is the desired output given the above input data.

   result
D  -7.679
F   4.342
A  -6.770
E  -0.093
B   6.110
C   5.670
like image 422
themachinist Avatar asked Oct 12 '16 07:10

themachinist


People also ask

Does pandas Tolist preserve order?

Order will always be preserved. When you use the list function, you provide it an iterator, and construct a list by iterating over it.

How do I sort pandas DataFrame rows?

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 rearrange the order of a data frame?

You need to create a new list of your columns in the desired order, then use df = df[cols] to rearrange the columns in this new order.


1 Answers

You could use argsort with kind='mergesort' to get sorted row indices that keeps the order and then simply index into the dataframe with those for the desired output, like so -

df.iloc[new_order.argsort(kind='mergesort')]

Sample run -

In [2]: df
Out[2]: 
   result
A  -6.770
B   6.110
C   5.670
D  -7.679
E  -0.093
F   4.342

In [3]: df.iloc[new_order.argsort(kind='mergesort')]
Out[3]: 
   result
D  -7.679
F   4.342
A  -6.770
E  -0.093
B   6.110
C   5.670
like image 53
Divakar Avatar answered Dec 29 '22 16:12

Divakar