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

Pandas – dataframe with column with dictionary, save value instead

I have the below stories_data dictionary, which I’m able to create a df from but since owner is a dictionary as well I would like to get the value of that dictionary so the owner column would have 178413540

import numpy as np 
import pandas as pd

stories_data = {'caption': 'Tel_gusto', 'like_count': 0, 'owner': {'id': '178413540'}, 'headers': {'Content-Encoding': 'gzip'}

x = pd.DataFrame(stories_data.items())
x.set_index(0, inplace=True)
stories_metric_df = x.transpose()

del stories_metric_df['headers']

I’ve tried this but it gets the key not the value

stories_metric_df['owner'].explode().apply(pd.Series)

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

>Solution :

You can use .str, even for objects/dicts:

stories_metric_df['owner'] = stories_metric_df['owner'].str['id']

Output:

>>> stories_metric_df
0    caption like_count      owner
1  Tel_gusto          0  178413540

Another solution would be to skip the explode, and just extract id:

stories_metric_df['owner'].apply(pd.Series)['id']

although I suspect my first solution would be faster.

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