To access an element in a Series, specify the Series name followed by the element’s index within square brackets, as shown here:
print(emps_names[9001])
This outputs the element corresponding to index 9001:
Jeff Russell
Alternatively, you can use the loc property of the Series object:
print(emps_names.loc[9001])
Although you’re using custom indices in this Series object, you can still access its elements by position (that is, use integer location–based indexing) via the iloc property. Here, for example, you print the first element in the Series:
print(emps_names.iloc[0])
You can access multiple elements by their indices with a slice operation:
print(emps_names.loc[9001:9002])
This produces the following output:
9001 Jeff Russell
9002 Jane Boorman
Notice that slicing with loc includes the right endpoint (in this case, index 9002), whereas usually Python slice syntax does not.
You can also use slicing to define the range of elements by position rather than by index. For instance, the preceding results could instead be generated by the following code:
print(emps_names.iloc[0:2])
or simply as follows:
print(emps_names[0:2])
As you can see, unlike slicing with loc, slicing with [] or iloc works the same as usual Python slicing: the start position is included but the stop is not. Thus, [0:2] leaves out the element in position 2 and returns only the first two elements.
0 comments:
Post a Comment