Python Pandas:将嵌套字典转换为数据框

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/31460234/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-13 23:37:59  来源:igfitidea点击:

Python Pandas: Convert nested dictionary to dataframe

pythondictionarypandasnested

提问by UserYmY

I have a dic like this:

我有一个这样的 dic:

{1 : {'tp': 26, 'fp': 112},
2 : {'tp': 26, 'fp': 91},
3 : {'tp': 23, 'fp': 74}}

and I would like to convert in into a dataframe like this:

我想转换成这样的数据帧:

t tp fp
1 26  112
2 26  91
3 23  74

Does anybody know how?

有人知道怎么做吗?

回答by Anand S Kumar

Try DataFrame.from_dict()and with keyword argument orientas 'index'-

尝试DataFrame.from_dict()使用关键字参数orient作为'index'-

Example -

例子 -

In [20]: d = {1 : {'tp': 26, 'fp': 112},
   ....: 2 : {'tp': 26, 'fp': 91},
   ....: 3 : {'tp': 23, 'fp': 74}}

In [24]: df =pd.DataFrame.from_dict(d,orient='index')

In [25]: df
Out[25]:
   tp   fp
1  26  112
2  26   91
3  23   74

If you also want to set the column name for indexcolumn , use - df.index.name, Example -

如果您还想为indexcolumn设置列名,请使用 - df.index.name,示例 -

In [30]: df.index.name = 't'

In [31]: df
Out[31]:
   tp   fp
t
1  26  112
2  26   91
3  23   74