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

Use*_*YmY 2 python dictionary nested pandas

我有一个像这样的词:

{1 : {'tp': 26, 'fp': 112},
2 : {'tp': 26, 'fp': 91},
3 : {'tp': 23, 'fp': 74}}
Run Code Online (Sandbox Code Playgroud)

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

t tp fp
1 26  112
2 26  91
3 23  74
Run Code Online (Sandbox Code Playgroud)

有人知道吗?

Ana*_*mar 8

尝试DataFrame.from_dict()与关键字参数orient'index'-

示例 -

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
Run Code Online (Sandbox Code Playgroud)

如果您还想为index列设置列名,请使用 - 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
Run Code Online (Sandbox Code Playgroud)