将字典字典中的单个条目转换为数据框,其中键是列

Moh*_*afa 3 python dictionary dataframe pandas

给定一个字典,例如:

records = {0:{'name':'John', 'salary':'5000'}, 1:{'name':'Bob', 'salary':'3500'}}
Run Code Online (Sandbox Code Playgroud)

如果我想获取并存储(在 csv 中)一个数据框,例如:

name  salary
John   5000
Run Code Online (Sandbox Code Playgroud)

通过使用记录 [0] 作为访问内部字典的方式,我该怎么做?

我试过了:

df = pd.DataFrame(records[0], index=[0])

df= pd.DataFrame(list(records[0].values()), columns=list(records[0].keys()))

df= pd.DataFrame.from_dict(records[key], orient='columns')
Run Code Online (Sandbox Code Playgroud)

但是他们都没有按预期工作(第二个给了我一个错误,第一个和最后一个只有一列)

jez*_*ael 6

使用DataFrame.from_dictorient='index'

df = pd.DataFrame.from_dict(records, orient='index')
print (df)
   name salary
0  John   5000
1   Bob   3500
Run Code Online (Sandbox Code Playgroud)

编辑 - 对于record传递给嵌套列表的第一个值:

df = pd.DataFrame([records[0]])
print (df)
   name salary
0  John   5000
Run Code Online (Sandbox Code Playgroud)