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

Time:03-01

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:

"{'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) ?

CodePudding user response:

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
  • Related