[英]Convert DataFrame to Dictionary Containing List
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.
将ID设置为键,并将数据帧中的行记录作为值。
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.
首先,我将使用group by,然后使用for循环,我将得到想要的结果,遍历结果。
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. 这给了我以下输出。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.