Home > Software engineering >  Unpack nested Dictionary in Column DataFrame Pandas
Unpack nested Dictionary in Column DataFrame Pandas

Time:05-30

I have a DataFrame like this

pd.DataFrame([{'ISO3': 'AFG', 'indicator_value': {'137506':{'2012':0.489, '2014':0.49}}}])

enter image description here

While I need a DataFrame in this format:

pd.DataFrame([{'indicator_ID':137506, 'ISO3': 'AFG', '2012': 0.489, '2014':0.49}, 
             {'indicator_ID':137506, 'ISO3': 'ALB', '2012': 0.49, '2014':0.5}])

enter image description here

CodePudding user response:

Try this

df = pd.DataFrame([{'ISO3': 'AFG', 'indicator_value': {'137506':{'2012':0.489, '2014':0.49}}}])

# reformat column indicator_value into a list of dictionaries
# and build a df
res = pd.DataFrame([{'indicator_ID': k, **d[k]} for d in df['indicator_value'] for k in d])
# insert ISO3 column
res.insert(1,'ISO3', df.ISO3)
res

enter image description here

  • Related