简体   繁体   English

嵌套字典列表中的 pandas 多索引 DataFrame

[英]pandas multiindex DataFrame from list of nested dictionaries

I have a list of nested dictionaries我有一个嵌套字典列表

lst = [{'a':{'aa':1,'ab':2},'b':{'ba':3,'bb':4}}]*2

I am struggling to get a pandas DataFrame with mutltiindex columns.我正在努力获得带有 multiindex 列的 pandas DataFrame。

Currently I am doing:目前我正在做:

pd.concat([pd.DataFrame.from_dict(dct,orient='index').stack().to_frame().T for dct in lst])

and the output is (and shall be) output 是(并且应该是) 在此处输入图像描述

But there got to be a simpler line I guess, this one is ugly, cannot figure out right now.但我猜必须有一条更简单的线,这条线很难看,现在无法弄清楚。 Any help is welcome.欢迎任何帮助。 Thx.谢谢。

Use nested list with dict comprehension and then recreate MultiIndex :将嵌套列表与字典理解结合使用,然后重新创建MultiIndex

df = pd.DataFrame([{(k,k1): v1 for k, v in x.items() for k1, v1 in v.items()} for x in lst])
df.columns = pd.MultiIndex.from_tuples(df.columns)
print (df)
   a     b   
  aa ab ba bb
0  1  2  3  4
1  1  2  3  4

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM