将字典转换为数据帧,键作为列名,键的值作为数据帧的列值



将嵌套字典转换为数据帧,其中,dictionary键为列名,而与这些键对应的则为数据帧的

column值我是python的新手,尝试过几种方法,但都失败了,请帮忙。

dict = {
'sheet1': {
'col1': ['a', 'b', 'c', 'd', 'e'],
'col2': ['p', 'q', 'r', 's', 't'],
'col3': ['l', 'm', 'n', 'o'],
'col4': ['e', 'b', 'w', 't', 'b']
},
'sheet2': {
'col1': ['r', 'w', 'y', 'g', 'r'],
'col2': ['q', 'y', 'f', 'w'],
'col3': ['w', 'g', 4, 2, 'd']
}
}
output: 
col1    col2   col3   col4
a       p       l      e
b       q       m      b
c       r       n      w
d       s       o      t
e       t       nan    b
r       q       w      nan
w       y       g      nan
y       f       4      nan
g       w       2      nan
r      nan      d      nan

您可以通过从嵌套字典创建多个数据帧,并使用pd.concat将它们连接起来来实现这一点。例如:

>>> data = {
...     'sheet1': {'col1': [1, 2, 3, 4], 'col2': [5, 6, 7, 8]},
...     'sheet2': {'col1': [11, 12, 13, 14], 'col2': [15, 16, 17, 18]},
... }
>>> df = pd.concat([pd.DataFrame(d) for d in data.values()], ignore_index=True)
>>> df
col1  col2
0     1     5
1     2     6
2     3     7
3     4     8
4    11    15
5    12    16
6    13    17
7    14    18

您可以从给定的字典中创建嵌套的数据帧,然后将它们相互连接。

这是示例字典,

sample_dict = {
'sheet1': {
'col1': ['a', 'b', 'c', 'd', 'e'],
'col2': ['p', 'q', 'r', 's', 't'],
'col3': ['l', 'm', 'n', 'o']
},
'sheet2': {
'col1': ['r', 'w', 'y', 'g', 'r'],
'col2': ['q', 'y', 'f', 'w'],
'col3': ['w', 'g', 4, 2, 'd'],
'col4': ['e', 'b', 'w', 't', 'b']
}
}

然后,您可以为sample_dict、中的每个键制作一个数据帧列表

df_list=[]
for key in sample_dict:
df_list.append(pd.DataFrame(dict([ (k,pd.Series(v)) for k,v in sample_dict[key].items()])))

最后,连接存储在df_list,中的数据帧

final_df=pd.concat(df_list)

最新更新