w3resource

Pandas Data Series: Convert a dictionary to a Pandas series

Pandas: Data Series Exercise-5 with Solution

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.

Python-Pandas Code Editor:

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

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.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://www.w3resource.com/python-exercises/pandas/python-pandas-data-series-exercise-5.php