Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create dictionary with key from one dataframe column and values from another dataframe column

I have the following df and wish to create a dictionary with clust as the key and Feature as a list of the values. How would I go about creating the desired dict?

df

   Feature  clust
0      I_0      2
1      I_1      3
2      I_2      1
3      I_3      1
4      I_4      2
5      N_0      3
6      N_1      3

desired dict

{1: ['I_2','I_3'],
 2: ['I_0','I_4'], 
 3: ['I_1','N_0','N_1']}

Cheers :)

like image 263
oceanbeach96 Avatar asked Mar 14 '26 05:03

oceanbeach96


1 Answers

First aggregate list for Series and then convert it to dictionary:

desired dict = df.groupby('clust')['Feature'].agg(list).to_dict()
like image 146
jezrael Avatar answered Mar 16 '26 03:03

jezrael