Pandas series is a one-dimensional data structure. It can hold data of many types including objects, floats, strings and integers. You can create a series by calling pandas.Series().

An list, numpy array, dict can be turned into a pandas series. You should use the simplest data structure that meets your needs. In this article we’ll discuss the series data structure.

Related course: Data Analysis with Python Pandas

Create series

Introduction

Pandas comes with many data structures for processing data. One of them is a series.
The syntax for a series is:

1
2
3
import pandas as pd
s = pd.Series()
print(s)

This creates an empty series.

Create series from list

To turn a list into a series, all you have to do is:

1
2
3
>>> import pandas as pd
>>> items = [1,2,3,4]
>>> s = pd.Series(items)

The contents of s is:

0 1
1 2
2 3
3 4
dtype: int64

By default is assigns an index. First it shows the index, then the element value.

Create series from ndarray

You can create a series from a numpy ndarray.

1
2
3
4
>>> import pandas as pd
>>> import numpy as np
>>> data = np.array(['x','y','z'])
>>> s = pd.Series(data)

This ouputs the following:

1
2
3
4
5
6
>>> s
0 x
1 y
2 z
dtype: object
>>>

Create a series from a dict

If you have a dictionary, you can turn it into a series:

1
2
3
4
>>> import pandas as pd
>>> import numpy as np
>>> data = { 'uk':'united kingdom','fr':'france' }
>>> s = pd.Series(data)

The contents of the series is as follows:

1
2
3
4
5
>>> s
uk united kingdom
fr france
dtype: object
>>>

As index it used the dictionary keys.

Pandas series

Pandas series get index

You can access series data like you would with a list or ndarray.

1
2
3
4
5
6
7
8
9
>>> import pandas as pd
>>> import numpy as np
>>> data = np.array(['x','y','z'])
>>> s = pd.Series(data)
>>> s[0]
'x'
>>> s[1]
'y'
>>>

You slice a series, like you would with a list:

1
2
3
4
5
6
7
>>> data = np.array([1,2,3,4,5,6])
>>> s = pd.Series(data)
>>> s[:3]
0 1
1 2
2 3
dtype: int64
1
2
3
4
5
>>> s[3:5]
3 4
4 5
dtype: int64
>>>

Related course: Data Analysis with Python Pandas