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

Pandas dataframe to dictionary with conditions

I have this small dataframe:

PROCESS PROCEDURE   SUB_PROCEDURE
---------------------------------
      A       NaN              S1
      B        P1              S2
      C        P2              S3
      D       NaN              S4

I would like to obtain a dictionary that, if the value in column ‘PROCEDURE’ is empty, the key, value pair consists of

PROCESS: SUB_PROCEDURE 

and if there is something in the ‘PROCEDURE’ column:

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

'PROCESS' : {'PROCEDURE': SUB_PROCEDURE}.

This is how it would show for the above dataframe:

desired_output = {
    'A': 'S1',
    'B': {'P1': 'S2'},
    'C': {'P1': 'S2'},
    'D': 'S4'
} 

This is what I’ve tried so far:

df_so.set_index('PROCESS')[['PROCEDURE', 'SUB_PROCEDURE']].to_dict()

>Solution :

Use dict comprehension with if condition:

desired_output = {a: {b:c} if pd.notna(b) else c  for a, b,c in df.to_numpy()}
print (desired_output)
{'A': 'S1', 'B': {'P1': 'S2'}, 'C': {'P2': 'S3'}, 'D': 'S4'}
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