Stack Team! I have a data frame that I'd like to convert into a dictionary with one of the columns as the key and the values of another column appended to a list within the dictionary.
I've been able to convert the data frame into a dictionary with key value pairs for each row of the data frame, but I simply need a series or list appended to a series belonging to each dictionary key.
DataFrame:
Team Name ID
0 Idaho 1234
1 Idaho 5678
2 Tokyo 5432
Tried this and I get a dictionary containing dictionaries. The ID are set to keys with the row records from the data frame as values.
Code Attempt:
team_id_df.set_index('Team Name').to_dict(orient='index')
Result:
{'Idaho': {'ID': 1234, 'ID': 5678}, 'Tokyo': { 'ID': 5432}}
But I'm trying to get this:
{'Idaho': [1234, 5678],'Tokyo': [5432]}
I'm a little stumped, any suggestions for making this transformation?
I would have done it in two steps. First I would have used a group by and then using a for loop, I will get what I want, iterating over the results.
b = a.groupby(by=['Team Name','ID']).agg('count')
final_dict = {}
for team_name, ID in b.index:
final_dict.setdefault(team_name,[]).append(ID)
print(final_dict)
This gave me the following output.
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.