Skip to content
Home » pandas Part 2 – the Series Class

pandas Part 2 – the Series Class

Spread the love

Series class

In the previous part we installed pandas, or, if you have the Anaconda distribution of Python, we just made it clear that we already have it. In this part we’ll be talking about the Series class, which is one of the fundamental data types in pandas.

As pandas is built on numpy, we’ll import these two modules at the beginning of each part from now on:

In [1]:
import numpy as np
import pandas as pd

So, what is a pandas Series? It’s a one-dimensional array of indexed data. Let’s create one so that you can see what indexed data means. You can create a Series object in a couple of ways, like from a list or numpy array. Let’s start with a list:

In [2]:
nums = pd.Series([2.35, 4.11, 0.87, 2.76, 3.12, 5.79])
nums
Out[2]:
0    2.35
1    4.11
2    0.87
3    2.76
4    3.12
5    5.79
dtype: float64

As you can see, the Series object we just created contains not only the elements from the list, but also their indices. That’s what indexed data means. Besides, we can see the dtype of our elements, which in this case are floats.

Now, we can access just the values or just the indices if we need to. To do it, we will use the values and index attributes respectively:

In [3]:
# values
nums.values
Out[3]:
array([2.35, 4.11, 0.87, 2.76, 3.12, 5.79])
In [4]:
# indices
nums.index
Out[4]:
RangeIndex(start=0, stop=6, step=1)

The values are returned as a one-dimensional numpy array, and the indices as a pandas Index object, which we are going to discuss in more detail in one of the articles in this series in near future:

In [5]:
type(nums.values), type(nums.index)
Out[5]:
(numpy.ndarray, pandas.core.indexes.range.RangeIndex)

OPERATIONS ON SERIES OBJECTS

Accessing particular elements of a pandas Series object is easy. You just use square brackets:

In [6]:
# access element at index 2
nums[2]
Out[6]:
0.87

Slicing is pretty straightforward too:

In [7]:
# slice from index 1 to index 4 (the latter not being included)
nums[1:4]
Out[7]:
1    4.11
2    0.87
3    2.76
dtype: float64

These are just the basics of Series in pandas. In the next part of this pandas series we’ll see how we can create Series objects. You already know you can use a list or numpy array to this end, but that’s not all.

Your Panda3D Magazine

Make Awesome Games and Other 3D Apps

with Panda3D and Blender using Python.

Cool stuff, easy to follow articles.

Get the magazine here (PDF).

Python Jumpstart Course

Learn the basics of Python, including OOP.

with lots of exercises, easy to follow

The course is available on Udemy.

Blender Jumpstart Course

Learn the basics of 3D modeling in Blender.

step-by-step, easy to follow, visually rich

The course is available on Udemy and on Skillshare.

Here’s the video version of this article:


Spread the love
Tags:

Leave a Reply