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.
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
Asked: 2022-04-08 11:00:00 +0000
Seen: 11 times
Last updated: Oct 21 '21
How can I turn a string of characters into a list using R?
What causes a syntax error in a for loop and array in Pine Script?
Investigate the usage of square brackets.
How can Google calendar events be generated on the server-side using Flutter?
How can the dataframe be transformed into a record list without including brackets?
How can brackets in a filepath be managed when it is passed as a variable in the pipeline in Bash?