Ask Your Question
0

What is the process for constructing a dictionary using two columns from pandas DataFrame?

asked 2022-04-08 11:00:00 +0000

david gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
0

answered 2021-10-21 11:00:00 +0000

lalupa gravatar image

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.

edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2022-04-08 11:00:00 +0000

Seen: 11 times

Last updated: Oct 21 '21