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 list of JSON element to python array

I have a dataframe like so:

Store matches
Murphy’s [{‘domain’: ‘murphyscolumbus.com’, ‘location’: ‘Columbus, OH’}, {‘domain’: ‘murphystampa.com’, ‘location’: ‘Tampa, FL’}]
Bill’s [{‘domain’: ‘billsdallas.com’, ‘location’: ‘Dallas, TX’}, {‘domain’: ‘billsorlando.com’, ‘location’: ‘Orlando, FL’}]

What I want is a dataframe like so:

Store domains
Murphy’s [‘murphyscolumbus.com’, ‘murphystampa.com’]
Bill’s [‘billsdallas.com’,’billsorlando.com’]

I’m hoping for something less computationally expensive than something like a for loop that steps through as the dataframe is quite large.

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

>Solution :

Try:

from ast import literal_eval

# apply literal_eval if necessary
df["matches"] = df["matches"].apply(literal_eval)

df["domains"] = df.pop("matches").apply(lambda x: [d["domain"] for d in x])
print(df)

Prints:

      Store                                  domains
0  Murphy's  [murphyscolumbus.com, murphystampa.com]
1    Bill's      [billsdallas.com, billsorlando.com]
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