How to Create Pandas Series from a dictionary with indexes in a specific order?


If you try to create a pandas Series object by using a python dictionary, the indices and values order of the series will depend on the order of key-value pairs in the dictionary.

In order to set the specific index order in the series object, we can use the index attribute of the pandas Series method at the time of series creation.

Let’s take an example and create a pandas Series with specific index order by using a python dictionary. To do this first we need to create a dictionary.

Example

import pandas as pd

# Creating dictionary
dictionary = {'a': 64,'b': 23,'c': 13,'d': 85,'e': 14}

# Creating Series with specific index order
s = pd.Series(dictionary, index=['c', 'd', 'b', 'e', 'a'])
print(s)

Explanation

As the index argument contains the list of strings that are the same items from dictionary keys but in a different order. So a Series object will be created from the dictionary’s key-value pairs but the order will not be the same as the dictionary data.

Series constructor will create a new Series object, by following the order of items in the index argument of pandas Series constructor.

Output

c   13
d   85
b   23
e   14
a   64

The indexes c, d, b, e, a are ordered by using data from the index argument of the pandas Series method.

Let’s take another example and create a new pandas Series by using integer index values.

Example

import pandas as pd

# Creating dictionary
dictionary = {1: 56,2: 32,3: 34,4: 75,5: 14}

# Creating Series with specific index order of all integers
s = pd.Series(dictionary, index=[3,5,1,2,4])
print(s)

Explanation

In this example, the values in our dictionary are integers, all keys and values are integers only. And we created a Series object by using this dictionary, also specified the order of the series index by using the index argument of the pandas Series method.

Output

3   34
5   14
1   56
2   32
4   75
dtype: int64

The values 3, 5, 1, 2, and 4 are index values, this order is given by the index argument of the series method. The above two examples are used to specify the particular order of the Series object.

Updated on: 17-Nov-2021

449 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements