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.
Practice now: Test your Python skills with interactive challenges
Create series
Introduction
Pandas comes with many data structures for processing data. One of them is a series. The syntax for a series is:
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:
>>> 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.
>>> import pandas as pd
>>> import numpy as np
>>> data = np.array(['x','y','z'])
>>> s = pd.Series(data)
This ouputs the following:
>>> 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:
>>> 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:
>>> 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.
>>> 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:
>>> data = np.array([1,2,3,4,5,6])
>>> s = pd.Series(data)
>>> s[:3]
0 1
1 2
2 3
dtype: int64
>>> s[3:5]
3 4
4 5
dtype: int64
>>>
Practice now: Test your Python skills with interactive challenges