pandas Slicing with labels


Example

When using labels, both the start and the stop are included in the results.

import pandas as pd
import numpy as np
np.random.seed(5)
df = pd.DataFrame(np.random.randint(100, size=(5, 5)), columns = list("ABCDE"), 
                  index = ["R" + str(i) for i in range(5)])

# Out: 
#      A   B   C   D   E
# R0  99  78  61  16  73
# R1   8  62  27  30  80
# R2   7  76  15  53  80
# R3  27  44  77  75  65
# R4  47  30  84  86  18

Rows R0 to R2:

df.loc['R0':'R2']
# Out: 
#      A   B   C   D   E
# R0   9  41  62   1  82
# R1  16  78   5  58   0
# R2  80   4  36  51  27

Notice how loc differs from iloc because iloc excludes the end index

df.loc['R0':'R2'] # rows labelled R0, R1, R2
# Out: 
#      A   B   C   D   E
# R0   9  41  62   1  82
# R1  16  78   5  58   0
# R2  80   4  36  51  27


# df.iloc[0:2] # rows indexed by 0, 1
#      A   B   C   D   E
# R0  99  78  61  16  73
# R1   8  62  27  30  80

Columns C to E:

df.loc[:, 'C':'E']
# Out: 
#      C   D   E
# R0  62   1  82
# R1   5  58   0
# R2  36  51  27
# R3  68  38  83
# R4   7  30  62