我有一个这样的dic:
{1 : {'tp': 26, 'fp': 112},
2 : {'tp': 26, 'fp': 91},
3 : {'tp': 23, 'fp': 74}}
我想将其转换成这样的数据框:
t tp fp
1 26 112
2 26 91
3 23 74
有人知道吗?
最佳答案
尝试 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
如果您还想为 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
关于 python Pandas : Convert nested dictionary to dataframe,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31460234/