We can easily convert a Pandas DataFrame into a Python dictionary using the to_dict()
method. This method can accept several parameters to customize the format of the dictionary, such as the orientation and the structure.
Here's an example code snippet:
main.py233 chars10 lines
In this example, we created a simple DataFrame with two columns (name
and age
). We then used the to_dict()
method with the orient
parameter set to 'records'
to create a list of dictionaries, where each dictionary contains the values of a single row in the DataFrame.
The output of this code snippet should be:
main.py91 chars2 lines
Note that the keys of the dictionaries in the resulting list correspond to the column names of the DataFrame. If you want to use a different column as the key, you can use the to_dict()
method with the orient
parameter set to 'index'
and pass the column name as the columns
parameter.
gistlibby LogSnag