Python pandas slice dataframe by multiple index ranges Python pandas slice dataframe by multiple index ranges pandas pandas

Python pandas slice dataframe by multiple index ranges


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:

     a10  2011  2125  3526  3627  37


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)]    a10  2011  2125  3526  3627  37