I have a dataframe which looks like this:
name value
0 user_x 34
1 user_y 23
I need to create a single dictionary from the above dataframe as follows:
dict = {"user_x": 34, "user_y": 23}
I tried the code below. Let's say I have a DataFrame f:
f.to_dict(orient='dict') with output as:
{'value': {0: 34, 1: 23}, 'name': {0: 'user_x', 1: 'user_y'}}
f.to_dict(orient='dict') with output as:
{'value': {0: 34, 1: 23}, 'name': {0: 'user_x', 1: 'user_y'}}
dict = {"user_x": 34, "user_y": 23, ....}
Given the following data:
data = {'name' :["user_x", 'user_y'], 'value': [34,23]}
df = pd.DataFrame(data)
You can use a dictionary comprehension to get the exact output you want.
output_dict = {x:y for x,y in df.values}
print(output_dict)
{'user_y': 23, 'user_x': 34}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.