Pandas – Create a Pandas Series from a dictionary.

You have some data in a python dictionary and you want to create a pandas series from it. For example you have some fruits price data in a dictionary and you want to convert it to a pandas series.

Solution –

Create the dictionary –

Let’s first create a python dictionary.

fruits = {'Apple': 200,
         'Avocado': 200,
         'Banana': 40,
         'Coconut': 30,
         'Jackfruit': 500,
         'Orange': 70}
print(fruits)

Create pandas series –

To create a pandas series from a dictionary, we simply pass the dictionary to the pd.Series constructor.

# import pandas
import pandas as pd 

# create a dict
fruits = {'Apple': 200,
         'Avocado': 200,
         'Banana': 40,
         'Coconut': 30,
         'Jackfruit': 500,
         'Orange': 70}

# create pandas series from a dict
s1 = pd.Series(fruits)
print(s1)

Creating pandas Series with the Index Parameter –

By default pandas use the dictionary keys as the index of the series. If you want you can also change that. Let’s say you want to reorder the data from Orange to Apple.

# create the index
index = ['Orange','Jackfruit','Coconut','Banana','Avocado','Apple']

# create series with the index parameter
s2 = pd.Series(fruits, index=index)
print(s2)

Now, If I want to create a series with only Banana, Apple, and Avocado prices then just pass these 3 values to the index parameter when creating the series, and the rest of the fruits and their prices will be ignored by pandas.

# create the index
index = ['Avocado','Apple', 'Banana']

# create series with the index parameter
s3 = pd.Series(fruits, index=index)
print(s3)

And if you add a fruit data in the index parameter that is not in the dictionary, pandas will fill the price with a Nan value i.e. Not a number or missing value.

# create the index
index = ['Avocado','Apple', 'Banana', 'Watermelon']

# create series with the index parameter
s4 = pd.Series(fruits, index=index)
print(s4)

  1. Create a Pandas Series from a list.
  2. Create Pandas DataFrame from Lists.
  3. Create Pandas DataFrame from dictionary.
  4. Convert a Pandas DataFrame to a Dictionary.

Rating: 1 out of 5.

Leave a Reply