I'm trying to create a dictionary from a column containing set like
d = {'col1': [{'A','B'},{'C','D'},{'A','C'},{'C'}], 'col2': [3, 4,5,7]}
df = pd.DataFrame(data=d)
I want to apply something such that
df.apply(something)
I get
[{A:[3,5]}, {B:[3]}, {C:[4,5,7]},{D:[4]}]
Use melt, groupby + apply(list), and to_dict:
(pd.DataFrame(df.col1.tolist())
.join(df.col2)
.melt('col2')
.groupby('value')['col2']
.apply(list)
.to_dict())
# {'A': [5, 3], 'B': [3], 'C': [7, 4, 5], 'D': [4]}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With