Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to put elements of a pandas index as values of a dictionary?

I’m struggling with an error in pandas which is driving me crazy.

I want to build a dictionary which extracts some data from a pandas df:

Index_col  col1 
P1         F1-R1
P2         F1-R1
P3         F1-R1
P4         F1-R1
P5         F1-R2
P6         F1-R2
P7         F1-R2
P8         F1-R2
(etc)

Would give:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

{'F1-R1': ['P1', 'P2', 'P3', 'P4'],
 'F1-R2': ['P5', 'P6', 'P7', 'P8']}

However the following code:

dic = dict.fromkeys(df.col1.unique(), [])
for idx, row in df.iterrows():
    dic[row["col1"]].append(idx)

Produces

{'F1-R1': ['P1', 'P2', 'P3', 'P4', 'P5', 'P6', 'P7', 'P8']],
 'F1-R2': ['P1', 'P2', 'P3', 'P4', 'P5', 'P6', 'P7', 'P8']}

I can’t figure ut why :/. Does someone has an answer (or another way to proceed) ?

>Solution :

Just group by col1 and collect lists with converting the result into dict:

d = df.groupby('col1')['Index_col'].apply(list).to_dict()

{'F1-R1': ['P1', 'P2', 'P3', 'P4'], 'F1-R2': ['P5', 'P6', 'P7', 'P8']}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading