0

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

Willeke
  • 14,578
  • 4
  • 19
  • 47
  • Does this answer your question? [Split / Explode a column of dictionaries into separate columns with pandas](https://stackoverflow.com/questions/38231591/split-explode-a-column-of-dictionaries-into-separate-columns-with-pandas) – Rodalm May 29 '22 at 18:25
  • I think changing dict format is easiler – Seonghun May 29 '22 at 18:29

1 Answers1

1

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

cottontail
  • 10,268
  • 18
  • 50
  • 51