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 change a string containing a dict in pandas?

ID computed_data
0987 "{"Status":{"participate":14,"create":"10","activ":"0"},"rescount":22,"comcount":0,"partrate":0}"
4568 "{"Status":{"participate":49,"create":"40","activ":"27"},"rescount":22,"comcount":0,"partrate":73.47}"
1234 "{"Status":{"participate":3,"create":"3","activ":"1"},"comcount":0,"partrate":100,"rescount":42}"

I am trying to access and get the values in the computed_data column. It works on one cell when I am using eval().

eval(df["computed_data][0])

I tried a for loop to change all values at once and stored every dict in a list :

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

data = []
for x, i in enumerate(df["Computed Data"]):
    data.append(eval(df["Computed Data"][x]))

But I got an error "name "null" is not defined". I checked and I have no null values in my df which shape is 3601.

does anyone has an idea ? Thank you

>Solution :

Here is solution with custom function for convert not parseable strings to empty dictionaries:

import ast

def f(x):
    try:
        return ast.literal_eval(x)
    except ValueError:
        return {}
        
df["Computed Data"] = df[ "Computed Data"].str.strip('"').apply(f)
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