covnert a df in a dict in python

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.py
import pandas as pd

# create a sample DataFrame
df = pd.DataFrame({'name': ['Alice', 'Bob', 'Charlie'], 'age': [25, 30, 35]})

# convert the DataFrame to a dictionary
dict_from_df = df.to_dict(orient='records')

print(dict_from_df)
233 chars
10 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.py
[{'name': 'Alice', 'age': 25}, {'name': 'Bob', 'age': 30}, {'name': 'Charlie', 'age': 35}]
91 chars
2 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