Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

The process for constructing a dictionary using two columns from a pandas DataFrame involves using the to_dict() method, specifying the orient parameter as dict, and passing in the two columns as keys and values.

Here's an example code snippet:

import pandas as pd

# sample DataFrame
df = pd.DataFrame({'name': ['John', 'Jane', 'Bob'], 'age': [25, 30, 27]})

# construct dictionary
d = df[['name', 'age']].to_dict(orient='dict')

# print dictionary
print(d)

Output:

{'name': {0: 'John', 1: 'Jane', 2: 'Bob'}, 'age': {0: 25, 1: 30, 2: 27}}

In this example, we first create a sample DataFrame with two columns "name" and "age". Then, we select these two columns using double brackets and call the to_dict() method to transform the DataFrame into a dictionary with orient='dict'. Finally, we print the resulting dictionary.