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

Converting field under pandas column from str to dict and creating new column

I have a pandas column called geo inside a dataFrame called df. It can be populated or not.

geo has an object, referencing an id of a place.

I’m acessing row 18 using df.iloc[18].geo and it returns:

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

"{'place_id': '1c37515518593fe3'}"

its a str type.

How i can create a new column inside df called place_id countaining the value (on my example: 1c37515518593fe3) ?

>Solution :

This post should help you convert string literals into dictionaries:
Convert a String representation of a Dictionary to a dictionary?

EDIT updated for possible null values

import pandas as pd
import numpy as np
import ast

df = pd.DataFrame(data=["{'place_id': '1c37515518593fe3'}", np.NaN], columns=["geo"])
df["geo"] = df["geo"].apply(lambda x: ast.literal_eval(x) if not pd.isnull(x) else x)
df['place_id'] = df['geo'].apply(lambda x: x.get('place_id', np.NaN) if not pd.isnull(x) else x)
print(df)

                                geo          place_id
0  {'place_id': '1c37515518593fe3'}  1c37515518593fe3
1                               NaN               NaN
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