Range slicing

Slicing by supplying the start and end position to subset a range of values can be done in pandas objects, just as in NumPy arrays. The [ : ] operator helps in range slicing.

Let's slice the Series that we created earlier to subset the second, third, and fourth rows: 

ser[1:4]

This results in the following output:

Slicing a Series with a range of indexes

As always with a range in Python, the value after the colon is excluded when slicing.

Range slicing can be done by providing either the start or end index. If the end index is not provided, values are sliced from the given starting index to the end of the data structure. Likewise, when only the end index is given, the first row is considered as the starting position for slicing: 

# End provided for range slicing
df[:2]

This results in the following output:

Range slicing with the posterior end of the range defined

When the starting index is given, the row corresponding to that index value is chosen as the starting position for slicing:

# Start provided for range slicing
df[2:]

This results in the following output:

Range slicing with the anterior end of the range defined

Range slicing can be made even more interesting through a property to select rows at evenly spaced intervals. For instance, you can select only the odd-numbered rows or even-numbered rows this way:

# Select odd rows
df[::2]

This results in the following output:

Range slicing to select odd-numbered rows

To select even rows, you can use the following code:

# Select even rows
df[1::2]

This results in the following output:

Range slicing to select even-numbered rows

If you want to reverse the order of the rows, you can use the following command:

# Reverse the rows
df[::-1]

This results in the following output:

Range slicing to reverse the order of rows
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset