Python pandas slicing data across multiple index ranges

What is the pythonic way to truncate a data frame using more index ranges (e.g. 10:12 and 25:28 )? I want this more elegantly:

 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)] 

Thanks!

+11
source share
2 answers

You can use numpy r_ "slice trick":

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

gives:

  a 10 20 11 21 25 35 26 36 27 37 
+34
source

You can use the isin pandas 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 
+1
source

All Articles