scott martin
scott martin

Reputation: 1293

Extracting value from a Pandas column that is a dictionary

I have a Dataframe in the below format:

id, value
101, [{'id': 'ZWJ', 'type': 'user_reference', 'summary': 'Person 1'}]
102, [{'id': 'ZWS', 'type': 'user_reference', 'summary': 'Person 2'}]

I am trying to extract the value tagged to summary in each row.

Expected output :

id, name
101, Person 1
102, Person 2

Upvotes: 1

Views: 153

Answers (2)

jezrael
jezrael

Reputation: 862511

Use str[0] for get first list and then Series.str.get for value summary:

df['name'] = df['value'].str[0].str.get('summary')

print (df)
    id                                              value      name
0  101  [{'id': 'ZWJ', 'type': 'user_reference', 'summ...  Person 1
1  102  [{'id': 'ZWS', 'type': 'user_reference', 'summ...  Person 2

Details:

print (df['value'].str[0])
0    {'id': 'ZWJ', 'type': 'user_reference', 'summa...
1    {'id': 'ZWS', 'type': 'user_reference', 'summa...
Name: value, dtype: object

Upvotes: 2

scott martin
scott martin

Reputation: 1293

Got this fixed by

df['name'] = df.value(operator.itemgetter(0)).apply(operator.itemgetter('summary'))

Upvotes: 0

Related Questions