David López
David López

Reputation: 519

pandas create new columns from dictionaries

a portion of one column 'relatedWorkOrder' in my dataframe looks like this:

{'number': 2552, 'labor': {'name': 'IA001', 'code': '70M0901003'}...}
{'number': 2552, 'labor': {'name': 'IA001', 'code': '70M0901003'}...}
{'number': 2552, 'labor': {'name': 'IA001', 'code': '70M0901003'}...}

My desired output is to have a column 'name','labor_name','labor_code' with their respective values. I can do this using regex extract and replace:

df['name'] = df['relatedWorkOrder'].str.extract(r'{regex}',expand=False).str.replace('something','')

But I have several dictionaries in this column and in this way is tedious, also I'm wondering if it's possible doing this through accessing the keys and values of the dictionary

Any help with that?

Upvotes: 0

Views: 35

Answers (1)

a_guest
a_guest

Reputation: 36239

You can join the result from pd.json_normalize:

df.join(pd.json_normalize(df['relatedWorkOrder'], sep='_'))

Upvotes: 2

Related Questions