Getting/setting multiple contiguous values using slicing

Sometimes, the multiple values that we wish to get or set are coincidentally in neighboring (contiguous) columns. When this is the case, we can use slicing within the square brackets to select multiple values. With slicing, we specify the starting point and endpoint of the data that we wish to access. We can use slicing with both .loc and .iloc, although slicing using integers and .iloc is more common. The following lines of code illustrate slicing to retrieve part of a DataFrame (we can also assign elements using an equals sign). Note that slicing can also be used to access values in lists and tuples (as covered previously in the current chapter):

partial_df3 = df3.loc[1:3,'new_col2':'new_col4']
print(partial_df3)

The output is as follows:

   new_col2  new_col3  new_col4
1         0         7         7
2         0         9         1
3         0        11         1
..................Content has been hidden....................

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