Reorder pandas frame rows based on list and keep order

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 num_ array new_orderassigns each row one of three groups [0,1 or 2]. I would like to change the lines dfso that first lines appear in group 0, then 1, and finally 2. In each of the three groups, the initial ordering should remain unchanged.

At the beginning, df is organized 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 result, given the above input.

   result
D  -7.679
F   4.342
A  -6.770
E  -0.093
B   6.110
C   5.670
+4
source share
2 answers

You can use argsortc kind='mergesort'to get sorted row indices that keep order and then just index in a dataframe with those for the desired output, for example:

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

-

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
+4

pandas

df.set_index(new_order, append=True) \
    .sort_index(level=1) \
    .reset_index(1, drop=True)

enter image description here

  • new_order
    • set_index(new_order, append=True)
    • sort_index(level=1)
  • ,
    • reset_index(1, drop=True)
+2

Source: https://habr.com/ru/post/1657467/


All Articles