Python pandas slice dataframe by multiple index ranges

22,416

Solution 1

You can use numpy's r_ "slicing trick":

df = pd.DataFrame({'a':range(10,100)})
df.iloc[pd.np.r_[10:12, 25:28]]

NOTE: this now gives a warning The pandas.np module is deprecated and will be removed from pandas in a future version. Import numpy directly instead. To do that, you can import numpy as np and then slice the following way:

df.iloc[np.r_[10:12, 25:28]]

This gives:

     a
10  20
11  21
25  35
26  36
27  37

Solution 2

You can take advantage of pandas isin function.

df = pd.DataFrame({'a':range(10,100)})
ls = [i for i in range(10,12)] + [i for i in range(25,28)]
df[df.index.isin(ls)]


    a
10  20
11  21
25  35
26  36
27  37
Share:
22,416
ragesz
Author by

ragesz

Data scientist at Dmlab, Budapest, Hungary.

Updated on January 23, 2022

Comments

  • ragesz
    ragesz over 2 years

    What is the pythonic way to slice a dataframe by more index ranges (eg. by 10:12 and 25:28)?

    I want this in a more elegant way:

    df = pd.DataFrame({'a':range(10,100)})
    df.iloc[[i for i in range(10,12)] + [i for i in range(25,28)]]
    

    Result:

         a
    10  20
    11  21
    25  35
    26  36
    27  37
    

    Something like this would be more elegant:

    df.iloc[(10:12, 25:28)]