2.4 Slicing ranges

The most robust and consistent way of slicing ranges along arbitrary axes is described in the Selection by Position section detailing the .iloc method. For now, we explain the semantics of slicing using the [] operator.

With Series, the syntax works exactly as with an ndarray, returning a slice of the values and the corresponding labels:

In [1]: s
Out[1]: 
2000-01-01    0.4691
2000-01-02    1.2121
2000-01-03   -0.8618
2000-01-04    0.7216
2000-01-05   -0.4250
2000-01-06   -0.6737
2000-01-07    0.4047
2000-01-08   -0.3706
Freq: D, Name: A, dtype: float64

In [2]: s[:5]
Out[2]: 
2000-01-01    0.4691
2000-01-02    1.2121
2000-01-03   -0.8618
2000-01-04    0.7216
2000-01-05   -0.4250
Freq: D, Name: A, dtype: float64

In [3]: s[::2]
Out[3]: 
2000-01-01    0.4691
2000-01-03   -0.8618
2000-01-05   -0.4250
2000-01-07    0.4047
Freq: 2D, Name: A, dtype: float64

In [4]: s[::-1]
Out[4]: 
2000-01-08   -0.3706
2000-01-07    0.4047
2000-01-06   -0.6737
2000-01-05   -0.4250
2000-01-04    0.7216
2000-01-03   -0.8618
2000-01-02    1.2121
2000-01-01    0.4691
Freq: -1D, Name: A, dtype: float64

Note that setting works as well:

In [5]: s2 = s.copy()

In [6]: s2[:5] = 0

In [7]: s2
Out[7]: 
2000-01-01    0.0000
2000-01-02    0.0000
2000-01-03    0.0000
2000-01-04    0.0000
2000-01-05    0.0000
2000-01-06   -0.6737
2000-01-07    0.4047
2000-01-08   -0.3706
Freq: D, Name: A, dtype: float64

With DataFrame, slicing inside of [] slices the rows. This is provided largely as a convenience since it is such a common operation.

In [8]: df
Out[8]: 
                 A       B       C       D
2000-01-01  0.4691 -0.2829 -1.5091 -1.1356
2000-01-02  1.2121 -0.1732  0.1192 -1.0442
2000-01-03 -0.8618 -2.1046 -0.4949  1.0718
2000-01-04  0.7216 -0.7068 -1.0396  0.2719
2000-01-05 -0.4250  0.5670  0.2762 -1.0874
2000-01-06 -0.6737  0.1136 -1.4784  0.5250
2000-01-07  0.4047  0.5770 -1.7150 -1.0393
2000-01-08 -0.3706 -1.1579 -1.3443  0.8449

In [9]: df[:3]
Out[9]: 
                 A       B       C       D
2000-01-01  0.4691 -0.2829 -1.5091 -1.1356
2000-01-02  1.2121 -0.1732  0.1192 -1.0442
2000-01-03 -0.8618 -2.1046 -0.4949  1.0718

In [10]: df[::-1]
Out[10]: 
                 A       B       C       D
2000-01-08 -0.3706 -1.1579 -1.3443  0.8449
2000-01-07  0.4047  0.5770 -1.7150 -1.0393
2000-01-06 -0.6737  0.1136 -1.4784  0.5250
2000-01-05 -0.4250  0.5670  0.2762 -1.0874
2000-01-04  0.7216 -0.7068 -1.0396  0.2719
2000-01-03 -0.8618 -2.1046 -0.4949  1.0718
2000-01-02  1.2121 -0.1732  0.1192 -1.0442
2000-01-01  0.4691 -0.2829 -1.5091 -1.1356