Pandas list of JSON element to python array

Question:

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.

Asked By: Yabbadabbadooooo

||

Answers:

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]
Answered By: Andrej Kesely
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.