Delosari Delosari - 4 months ago 19
Python Question

Pandas dataframe: Getting row indeces from criteria 1, sorted by criteria 2

I have data frames with the following structure:

import pandas as pd
import numpy as np

data = {'Col1' : [4,5,6,7], 'Col2' : [10,20,30,40], 'Col3' : [100,50,-30,-50], 'Col4' : ['AAA', 'BBB', 'AAA', 'CCC']}

df = pd.DataFrame(data=data, index = ['R1','R2','R3','R4'])

Col1 Col2 Col3 Col4
R1 4 10 100 AAA
R2 5 20 50 BBB
R3 6 30 -30 AAA
R4 7 40 -50 CCC


I know how to get the row indeces from the rows in which
Col2
lies between 10 and 40:

indeces = (df.Col2 > 10) & (df.Col2 < 40)


However, how could I, for example, get those indeces sorted by the values in
Col4
?

Answer

You can use sort_values:

df[indeces].sort_values(['Col4'])

    Col1  Col2  Col3 Col4
R3     6    30   -30  AAA
R2     5    20    50  BBB
Comments