【问题标题】:Converting dictionary to dataframe with key as column names and value of key as column values of the dataframe将字典转换为数据框,键作为列名,键值作为数据框的列值
【发布时间】:2025-12-23 04:30:07
【问题描述】:

将嵌套字典转换为数据框,字典 keys 作为 列名values 对应于这些键的 column values 的数据框。

我是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

【问题讨论】:

  • 我认为您需要完成一些教程:您的 dict 格式不正确,将 dict 转储到 pandas 是 pandas 101。尝试:pandas.pydata.org/pandas-docs/stable/getting_started/…
  • 什么是 sheet1、col1、a 等?它们是来自其他地方的字符串还是变量?
  • 它们只是字符串

标签: python dataframe dictionary flatten


【解决方案1】:

您可以通过从嵌套字典创建多个数据框并使用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

【讨论】:

    【解决方案2】:

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

    这里是示例字典,

    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)
    

    【讨论】: