DataFrames are 2-dimensional data structure in pandas. DataFrames consists of rows, columns and the data. DataFrame can be created with the help of python dictionaries or lists but here we are going to learn how to create a list of dictionaries from pandas DataFrame.
For this purpose, pandas provide us pandas.DataFrame.to_dict() method, which will allow us to achieve this task.
pandas.DataFrame.to_dict() Method
This method is used to convert a DataFrame into list of dictionaries which will looks like a JSON.
Syntax:
DataFrame.to_dict(
orient='dict',
into=<class 'dict'>
)
Parameter(s): It takes few parameters like dict, list, series, split, records, index which are passed inside the method.
To work with pandas, we need to import pandas package first, below is the syntax:
import pandas as pd
Let us understand with the help of an example.
Output:
Original DataFrame: Players Format Runs 0 Sachin Test 15921 1 Ganguly Test 7212 2 Dravid Test 13228 3 Yuvraj Test 1900 4 Dhoni Test 4876 5 Kohli Test 8043 6 Sachin ODI 18426 7 Ganguly ODI 11363 8 Dravid ODI 10889 9 Yuvraj ODI 8701 10 Dhoni ODI 10773 11 Kohli ODI 12311 Converted Dictionary: {'Players': {0: 'Sachin', 1: 'Ganguly', 2: 'Dravid', 3: 'Yuvraj', 4: 'Dhoni', 5: 'Kohli', 6: 'Sachin', 7: 'Ganguly', 8: 'Dravid', 9: 'Yuvraj', 10: 'Dhoni', 11: 'Kohli'}, 'Format': {0: 'Test', 1: 'Test', 2: 'Test', 3: 'Test', 4: 'Test', 5: 'Test', 6: 'ODI', 7: 'ODI', 8: 'ODI', 9: 'ODI', 10: 'ODI', 11: 'ODI'}, 'Runs': {0: 15921, 1: 7212, 2: 13228, 3: 1900, 4: 4876, 5: 8043, 6: 18426, 7: 11363, 8: 10889, 9: 8701, 10: 10773, 11: 12311}}need an explanation for this answer? contact us directly to get an explanation for this answer