Create Dataframe from a nested dictionary

余生长醉 提交于 2021-02-05 07:22:25

问题


I am trying to create a dataframe from a list of values which has nested dictionaries So this is my data

 d=[{'user': 200,
 'p_val': {'a': 10, 'b': 200},
 'f_val': {'a': 20, 'b': 300},
 'life': 8},
  {'user': 202,
 'p_val': {'a': 100, 'b': 200},
 'f_val': {'a': 200, 'b': 300},
 'life': 8}]

i am trying to turn it into a dataframe as follows:

user new_col f_val   p_val life
200   a        20     10    8
200   b        300    200   8
202   a        200    100   8
202   b        300    200   8

I looked at other answers, none of them matched my requirement. The nearest I could find was this, and still did not work me. Any help would be much appreciated! Thank you


回答1:


Try

df = pd.concat([pd.DataFrame(e) for e in d])
df.reset_index().rename(columns={'index': 'newcol'})

newcol  user    p_val   f_val   life
0   a   200 10  20  8
1   b   200 200 300 8
2   a   202 100 200 8
3   b   202 200 300 8

The first line makes a DataFrame with the index being the a and b values. The second line makes this the newcol column.



来源:https://stackoverflow.com/questions/61277880/create-dataframe-from-a-nested-dictionary

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!