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)] 
                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.
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.
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 
                        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 
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With