Home > Enterprise >  Pandas - dataframe with column with dictionary, save value instead
Pandas - dataframe with column with dictionary, save value instead

Time:01-29

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)

CodePudding user response:

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.

  •  Tags:  
  • Related