First, you have to import Pandas!

import pandas as pd


Creating a Series

You create a series by passing a list of values.

my_series = pd.Series([98, 89, 60, 93])

my_series

 

0 98
1 89
2 60
3 93

 

The output shows both the index on the left (0-3) and the values on the right.

To replace the default numerical index with desired values when creating a new series, pass the index parameter with a list of values the same length as the series.

my_series2 = pd.Series([98, 89, 60, 93], index = ['A', 'B', 'C', 'D']) 

my_series2

 

A 98
B 89
C 60
D 93

 

Series – Selection & Slicing

Series can be indexed and sliced just liked strings, lists, and tuples.,/p>

my_series[1]
89

 

my_series[1:3]

 

1 89
2 60

 

If you have a custom index, you need to use the .loc[your_index_value] method to select a specific observation, or for slicing. When using the .loc[your_index_value] method for slicing, it returns the end value. Unlike traditional slicing where it returns one value before the end value. If confused, compare the example code and results above to the example code and results below.

my_series2.loc['B']
89

 

my_series2.loc['B':'C']

 

B 89
C 60

Series to Series Operations

For the full list of attributes and methods available to be used with series, see the official Pandas documentation which can be found here.

If using any of the math operators built into Python, the operation will be conducted element-wise within the same row. Meaning, the value at index 0 for series 1 will be added, subtracted, multiplied, or divided by the value at index 0 for series 2.

my_series3 = pd.Series([100, 200, 300, 400])

my_series3 + my_series

 

0 9800
1 17800
2 18000
3 37200