How to create a Pandas series from a python dictionary?

PandasServer Side ProgrammingProgramming

We can create a pandas Series object by using a python dictionary by sending the dictionary data to the pandas Series method i.e. pandas.Series(). This pandas Series method will create a new Series object with the keys and value pairs from the python dictionary.

All the keys in the dictionary will become the indices of the Series object, whereas all the values from the key-value pairs in the dictionary will become the values (data) of the Series object.

Let’s see an example to create a pandas Series with a python dictionary, to do this we need to create a python dictionary first.

Example

import pandas as pd
# Creating dictionary
dictionary = {'A':10, 'B':63, 'D':32, 'C':87}

# Creating Series
s = pd.Series(dictionary)
print(s)

Explanation

Here we initially created a python dictionary with key-value pairs of length 4, after that we passed the dictionary to the pandas Series object. Series is a pandas Series class constructor it will create a Series object, this object has index values from dictionary keys and values from dictionary values.

Output

A   10
B   63
D   32
C   87
dtype: int64

The above output block is the resultant Series object created by the pandas Series method using python dictionary, the data type of each element from the Series is having int64 type.

Let’s create another series object by using the index attribute of the pandas Serie method.

Example

import pandas as pd
# Creating dictionary
dictionary = {'A':10, 'B':89, 'C':43}

# Creating Series
s = pd.Series(dictionary, index=['A','B','C', 'D'])
print(s)

Explanation

In this example, we have created a series with a python dictionary of length 3, and additionally here we mentioned the index attribute to the Pandas Series object. The input to this index attribute is a list of strings and that has 4 elements in it.

Output

A   10.0
B   89.0
C   43.0
D    NaN
dtype: float64

In comparison to the previous example here the data type of all data in this series object is float64. This is because the elements in the dictionary and index attribute are not in the same length. Hence the pandas Series method will assign NaN value to that extra index, due to this the dtype of all elements is created to float64 dtype

raja
Updated on 17-Nov-2021 07:20:27

Advertisements