Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python pandas slice dataframe by multiple index ranges

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)] 
like image 528
ragesz Avatar asked Sep 08 '16 14:09

ragesz


People also ask

Can you group by index in pandas?

How to perform groupby index in pandas? Pass index name of the DataFrame as a parameter to groupby() function to group rows on an index. DataFrame. groupby() function takes string or list as a param to specify the group columns or index.

How do you slice a pandas DataFrame?

Slicing a DataFrame in Pandas includes the following steps:Ensure Python is installed (or install ActivePython) Import a dataset. Create a DataFrame. Slice the DataFrame.


2 Answers

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 
like image 142
Jon Clements Avatar answered Oct 20 '22 12:10

Jon Clements


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 
like image 23
KevinOelen Avatar answered Oct 20 '22 12:10

KevinOelen