python Pandas : Convert nested dictionary to dataframe

标签 python dictionary pandas nested

我有一个这样的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/

相关文章:

python - 创建字典列表并按字典中的值排序的正确方法

Python - 无法修改 Django Rest Framework 中的 serializer.data 字典

python - 继承 DataFrame 时如何为 'loc' 编写包装器方法

python - (Linux) 确定图像中不同颜色的百分比

python - 是否可以在自制的网络应用程序中单击?

python - SQLAlchemy:按关系过滤

python - 尝试使用 Keras 实现堆叠 LSTM 层时出现问题

javascript - 使用reduce和map获取数组中对象的频率

python - 在 Pandas DataFrame Python 中添加新列

python - 单独线程中的 Pandas pd.concat() 显示没有加速