Skill - Convert pandas Series to dictionary and vice-versa in python
Skills Required
- Setup python development environment
- Basic Printing in Python
- Commenting in Python
- Managing Variables in python
- Pandas DataFrame Basics
Please make sure to have all the skills mentioned above to understand and execute the code mentioned below. Go through the above skills if necessary for reference or revision
Pandas is a python library.
DataFrame is a data structure provided by the pandas library
Series is like a column of a pandas dataframe. It has index, values and a series name
The image shown below tries to describe the anatomy of a DataFrame
In this post we are going to learn how to convert a pandas series into a dictionary using the `to_dict` function on the series. Dictionary is a set of key value pairs. An example can be seen below
{
"firstname":"John",
"lastname": "Smith"
}
converting pandas series to dictionary using to_dict function
# import pandas module
import pandas as pd
# create a series for demonstration
s = pd.Series([1,2,3,4,5,6], index=['a', 'b', 'c', 'd', 'e', 'f'])
print('The series is')
print(s)
# convert series to dictionary using to_dict() function on series
sDict = s.to_dict()
print('The dictionary derived from series is ')
print(sDict)
# This should print
# {'a': 1, 'b': 2, 'c': 3, 'd': 4, 'e': 5, 'f': 6}
converting dictionary to a pandas series using pd.Series
import pandas as pd
d = {"firstName":"John", "lastName": "Doe"}
s = pd.Series(d)
print(s)
# this will print
"""
firstName John
lastName Doe
dtype: object
"""
Online Interpreter
Although we recommend to practice the above examples in Visual Studio Code, you can run these examples online at https://www.tutorialspoint.com/execute_python_online.php
Video
You can the video on this post here
References
- Official docs- https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.to_dict.html
Comments
Post a Comment