INDEXING IN SERIES
In this tutorial, we will be looking in depth about indexing in Series. We will achieve that by performing indexing operations on a Series. Furthermore, we will be using loc and iloc methods to know indexing in detail.
Performing Indexing in Series
This tutorial will discuss in detail about how to perform indexing of Series. It is important to understand that our index values don’t have to be whole numbers. We can perform indexing on strings as well. For example:
fruits = pd.Series([10,20,30,40,50], index=['apple','banana','orange','pear','peach'], name="Values") print(fruits)
Output:
apple 10 banana 20 orange 30 pear 40 peach 50 Name: Values, dtype: int64
In order to find the index-only values, you can use the index function along with the series name and in return you will get all the index values as well as datatype of the index.
fruits.index
Output:
Index(['apple', 'banana', 'orange', 'pear', 'peach'], dtype='object')
Above, you can see the data type of the index declared as an ‘object’. If the indexes were integers then the datatype would have been int.
Is Index Value Unique?
We can also check whether the index value in a Series is unique or not by using the is_unique() method in Pandas which will return our answer in Boolean (either True or False). If all values are unique then the output will return True, if values are identical then the output will return False. For example:
fruits.index.is_unique
Output:
True
Above, we can see that we have all the unique values are our indexes, hence the output is True.
Negative Indexing in Series
You can also access the element of a Series by adding negative indexing, for example to fetch the last element of the Series, you will call ‘-1’ as your index position and see what your output is:
fruits[-1]
Output:
50
Learn more about negative indexing in python here
iloc and loc Indexing in Series
iloc and loc methods are used for indexing labels and index positions respectively. iloc method is specifically used for indexing index position and never a label, otherwise an error will pop up as:
TypeError: Cannot index by location index with a non-integer key
Whereas, loc method is used for indexing only labels, so if you have indexes as strings or strings of even numbers as ‘12’, it’s always a good practice to use loc as an index method.
Let’s have a quick look at these examples separately:
For iloc:
Fruits.iloc[1]
Output:
20
For loc:
fruits.loc['apple']
Output:
10