从 Dataframe 的 2 列创建字典

Create dictionary from 2 columns of Dataframe

我有一个数据框:

df = pd.DataFrame({ 
'ID': ['1', '4', '4', '3', '3', '3'], 
'club': ['arts', 'math', 'theatre', 'poetry', 'dance', 'cricket']
})

注意:数据框的两列都可以有重复的值。

我想为每个级别及其独特的俱乐部名称创建一个字典字典。 它应该是这样的:

{
{'1':'arts'}, {'4':'math','theatre'}, {'3':'poetry','dance','cricket'}
}

请帮我解决这个问题

尝试 groupby() 然后 to_dict():

grouped = df.groupby("ID")["club"].apply(set)
print(grouped)
> ID
   1                      {arts}
   3    {cricket, poetry, dance}
   4             {math, theatre}

grouped_dict = grouped.to_dict()
print(grouped_dict)
> {'1': {'arts'}, '3': {'cricket', 'poetry', 'dance'}, '4': {'math', 'theatre'}}

编辑:

已更改为 .apply(set) 以获取套装。

您可以使用 defaultdict:

from collections import defaultdict
d = defaultdict(set)
for k,v in zip(df['ID'], df['club']):
    d[k].add(v)
dict(d)

输出:

{'1': {'arts'}, '4': {'math', 'theatre'}, '3': {'cricket', 'dance', 'poetry'}}

或者对于类似于提供的输出的格式:

[{k:v} for k,v in d.items()]

输出:

[{'1': {'arts'}},
 {'4': {'math', 'theatre'}},
 {'3': {'cricket', 'dance', 'poetry'}}]