我有这样的词:
{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
有人知道吗?
答案 0 :(得分:7)
尝试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
答案 1 :(得分:0)
我只是想说明一下(因为这是从嵌套字典转换为pandas数据框的主要结果之一),还有其他嵌套字典的方式也可以转换为数据框(例如,通过列嵌套) )。
例如以下嵌套字典
patients = {"Name":{"0":"John","1":"Nick","2":"Ali","3":"Joseph"},
"Gender":{"0":"Male","1":"Male","2":"Female","3":"Male"},
"Nationality":{"0":"UK","1":"French","2":"USA","3":"Brazil"},
"Age" :{"0":10,"1":25,"2":35,"3":29}}
可以使用orient ='columns'转换为熊猫数据框
df_patients = pd.DataFrame.from_dict(patients, orient='columns')