How to access elements in a Pandas series
This article is about accessing elements from a Pandas series in Python. Pandas series is a one-dimensional ndarray data structure. To use it, we first need to install the Pandas library. You can find detailed instructions to do that here. To access elements in the series, we are going to about 4 methods here. To list out the four methods, they are:
- Using .at – Index-based
- Using .loc – Index-based
- Using .iat – Position-based
- Using .iloc – Position-based
To check the successful installation of Pandas, execute the following line of code:
import pandas as pd
Before talking about the four methods, let’s initialize a series using the following line of Python code.
index=["zeroth", "first", "second", "third"] series = pd.Series(["a", "b", "c", "d"], index=index) print(series)
We can see the following output after executing this code:
zeroth a first b second c third d dtype: object
Let’s start by talking about the two index-based methods
Index-based methods to access elements:
1. Using .at
We specify the index in the square braces.
print("At third index: ", series.at["third"]) #index-based
At third index: d
2. Using .loc
Similarly, we mention the index in the square braces. Here we are going to use a for loop to access all the elements individually. Note that this way is more practical and helpful in solving problems. Here, the index is our defined list from the beginning
for i in index: #Index-based print(series.loc[i])
a b c d
Now that we have seen the index-based methods, let’s see the position-based methods.
Position-based methods to access elements:
3. Using iat
We specify the position number (an int) to access that specific element.
print("At third position: ", series.iat) #Position-based
At third position: d
4. Using iloc
Now, moving on to a more practical approach using a for loop.
for i in range(0, len(index)): #Position-based print(series.iloc[i])
a b c d
Note that these attributes are used differently in a data frame. These techniques are crucial for data analysis and data manipulation. It is important to know how to use these at ease without getting confused about positions and indexes. I hope that you could follow up on the article comfortably. If not, let me know in the comments.