Creating a Pandas Series from Dictionary
A Series is a one-dimensional labeled array capable of holding any data type (integers, strings, floating point numbers, Python objects, etc.). It has to be remembered that unlike Python lists, a Series will always contain data of the same type.
Let’s see how to create a Pandas Series from Dictionary.
Using Series() method without index parameter.
In this case, dictionary keys are taken in a sorted order to construct index.
Code #1 : Dictionary keys are given in sorted order.
# import the pandas lib as pdimport pandas as pd # create a dictionarydictionary = {'A' : 10, 'B' : 20, 'C' : 30} # create a seriesseries = pd.Series(dictionary) print(series) |
A 10 B 20 C 30 dtype: int64
Code #2 : Dictionary keys are given in unsorted order.
# import the pandas lib as pdimport pandas as pd # create a dictionarydictionary = {'D' : 10, 'B' : 20, 'C' : 30} # create a seriesseries = pd.Series(dictionary) print(series) |
B 20 C 30 D 10 dtype: int64
Using Series() method with index parameter.
In this case, the values in data corresponding to the labels in the index will be assigned.
Code #1 : Index list is passed of same length as the number of keys present in dictionary.
# import the pandas lib as pdimport pandas as pd # create a dictionarydictionary = {'A' : 50, 'B' : 10, 'C' : 80} # create a seriesseries = pd.Series(dictionary, index =['B', 'C', 'A']) print(series) |
B 10 C 80 A 50 dtype: int64
Code #2 : Index list is passed of greater length than the number of keys present in dictionary in this case, Index order is persisted and the missing element is filled with NaN (Not a Number).
# import the pandas lib as pdimport pandas as pd # create a dictionarydictionary = {'A' : 50, 'B' : 10, 'C' : 80} # create a seriesseries = pd.Series(dictionary, index =['B', 'C', 'D', 'A']) print(series) |
B 10 C 80 D NaN A 50 dtype: float64
Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.
To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course. And to begin with your Machine Learning Journey, join the Machine Learning - Basic Level Course


