How to Reference an Element of a Pandas Series Object in Python


In this article, we show how to reference an element of a pandas series object in Python.

A series object created in pandas is essentially a labeled list. A list that has a label, or index, attached to each element.

We've shown how to create a pandas series object.

Now how do we reference an element of a pandas series object?

And the answer is simple.

To reference an element of a pandas series object, all you have to do is called the name of the pandas series object followed by the index, or label, in brackets.

The best way to see this is in actual code.

In the following code below, we show how to reference elements of a pandas series object in Python.

A series object is an object that is a labeled list.

A series object is very similar to a list or an array, such as a numpy array, except each item has a label next to it. Another name for a label is an index.

The pandas module has this data called a series. All a series is is a labeled list, essentially.

Creating a series with the pandas module is very simple. All that is needed is the data. An optional second parameter is the labels that should appear next to each item in the list.

So let's go over a full example now of how to create a series with the pandas module in Python.

So let's now go over the code.

So we first have to import the pandas module. We do this with the line, import pandas as pd.

as pd means that we can reference the pandas module with pd instead of writing out the full pandas each time.

We create a variable, s1, which we set equal to, pd.Series([5,45,74])

Since we did not specify an index, the index is automatically set to an integer index beginning at an index of 0.

Thus, when we output, s1, we get a series object with an index starting at 0 and moving up 1 with each element.

Now to reference each individual element of the series object, we use the series object named followed by the index in brackets. s1[0] references the first element of the series object. s1[1] references the second element. s1[2] references the third element.

Now the first series object has an index composed of integers.

Next, we create a series object composed of strings. The strings are 'Seattle', 'Orlando', and 'Memphis'.

With this series object, we can reference individual elements in 1 of 2 ways. We can reference elements through integers starting with 0. Or we can reference elements by specifying the string index, such as s2['Seattle'], s2['Orlando'], s2['Memphis'].

So these are the ways we can reference an element of a pandas series object in Python.

Related Resources

How to Randomly Select From or Shuffle a List in Python

HTML Comment Box is loading comments...