我有一个字典列表,看起来像:
list_dict = [{'test1':{'a':1,'b':12,'c':40,'d':120,'e':20,'f':1,'g':2,'h':'2'}},
{'test2':{'a':5,'b':'10','c':20}},
{'test3':{'e':21,'f':'18','g':22,'h':20}}]
我想将其转换为这样的数据帧:键应该作为行,测试应该作为列。在没有其他测试的键的情况下,应使用NAN值填充
mac_type test1 test2 test3
a 1 5 NAN
b 12 10 NAN
c 40 20 NAN
d 120 NAN NAN
e 20 NAN 21
f 1 NAN 18
g 2 NAN 22
h 2 NAN 20
请帮助我。
将dict理解与平坦的嵌套dict一起使用,并传递给Dataframe
构造函数:
df = pd.DataFrame({k: v for x in list_dict for k, v in x.items()})
print (df)
test1 test2 test3
a 1 5 NaN
b 12 10 NaN
c 40 20 NaN
d 120 NaN NaN
e 20 NaN 21
f 1 NaN 18
g 2 NaN 22
h 2 NaN 20
或DataFrame
为每个嵌套的字典创建并传递给concat
,如果大型词典和许多外键会比第一个解决方案慢一些:
df = pd.concat([pd.DataFrame(x) for x in list_dict], axis=1)
print (df)
test1 test2 test3
a 1 5 NaN
b 12 10 NaN
c 40 20 NaN
d 120 NaN NaN
e 20 NaN 21
f 1 NaN 18
g 2 NaN 22
h 2 NaN 20
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句