w3resource

Pandas Data Series: Convert a dictionary to a Pandas series


5. Dict to Series

Write a Pandas program to convert a dictionary to a Pandas series.

Sample dictionary: d1 = {'a': 100, 'b': 200, 'c':300, 'd':400, 'e':800}

Sample Solution :

Python Code :

import pandas as pd
d1 = {'a': 100, 'b': 200, 'c':300, 'd':400, 'e':800}
print("Original dictionary:")
print(d1)
new_series = pd.Series(d1)
print("Converted series:")
print(new_series)

Sample Output:

Original dictionary:
{'a': 100, 'b': 200, 'c': 300, 'd': 400, 'e': 800}
Converted series:
a    100
b    200
c    300
d    400
e    800
dtype: int64                                 

Explanation:

In the above example –

d1 = {'a': 100, 'b': 200, 'c':300, 'd':400, 'e':800}: This line creates a Python dictionary 'd1' with five key-value pairs. Each key is a string ('a', 'b', 'c', 'd', 'e') and each value is an integer.

new_series = pd.Series(d1): This line creates a new Pandas Series object 'new_series' from the dictionary 'd1' using the pd.Series() constructor. The resulting Series object will have the same keys as the dictionary and the corresponding values as its elements.


For more Practice: Solve these Related Problems:

  • Write a Pandas program to convert a nested dictionary into a Series and flatten its hierarchical index.
  • Write a Pandas program to convert a dictionary with non-string keys to a Series and then convert the keys to strings.
  • Write a Pandas program to convert a dictionary with missing keys to a Series with a specified default value for missing keys.
  • Write a Pandas program to convert a dictionary to a Series and then sort the Series based on the dictionary values in descending order.

Go to:


Previous: Write a Pandas program to compare the elements of the two Pandas Series.
Next: Write a Pandas program to convert a NumPy array to a Pandas series.

Python-Pandas Code Editor:

Have another way to solve this solution? Contribute your code (and comments) through Disqus.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.