Python Pandas Series Example - Create or Initialize, Access
Pandas Series
Pandas Series is a one-dimensional labeled, homogeneously-typed array.
You can create a series with objects of any datatype. Be it integers, floats, strings, any datatype. You can have a mix of these datatypes in a single series.
In this tutorial, we will learn about Pandas Series with examples.
1. Create Pandas Series
To create Pandas Series in Python, pass a list of values to the Series() class. Pandas will create a default integer index.
In the following example, we will create a pandas Series with integers.
Python Program
import numpy as np
import pandas as pd
s = pd.Series([1, 3, 5, 12, 6, 8])
print(s)
Output
0 1
1 3
2 5
3 12
4 6
5 8
dtype: int64
The datatype of the elements in the Series is int64. Based on the values present in the series, the datatype of the series is decided.
2. Pandas Series with NaN values
You can also include numpy NaN values in pandas series.
In the following Pandas Series example, we will create a Series with one of the value as numpy.NaN.
Python Program
import numpy as np
import pandas as pd
s = pd.Series([1, 3, np.nan, 12, 6, 8])
print(s)
Output
0 1.0
1 3.0
2 NaN
3 12.0
4 6.0
5 8.0
dtype: float64
3. Pandas Series with Strings
You can include strings as well for elements in the series.
In the following example, we will create a Pandas Series with one of the value as string.
Python Program
import numpy as np
import pandas as pd
s = pd.Series(['python', 3, np.nan, 12, 6, 8])
print(s)
Output
0 python
1 3
2 NaN
3 12
4 6
5 8
dtype: object
As the elements belong to different datatypes, like integer and string, the datatype of all the elements in this pandas series is considered as object. But when you access the elements individually, the corresponding datatype is returned, like int64, str, float, etc.
4. Access Elements of Pandas Series
You can access elements of a Pandas Series using index.
In the following Pandas Series example, we create a series and access the elements using index.
Python Program
import numpy as np
import pandas as pd
s = pd.Series(['python', 3, np.nan, 12, 6, 8])
print(s[0])
print(s[4])
Output
python
6
Summary
In this tutorial of Python Examples, we learned how to create a Pandas Series with elements belonging to different datatypes, and access the elements of the Series using index, with the help of well detailed examples.