解压列 DataFrame 中的嵌套字典 Pandas

Unpack nested Dictionary in Column DataFrame Pandas

我有一个像这样的 DataFrame

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

虽然我需要这种格式的 DataFrame:

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

试试这个

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