【问题标题】:How to convert dictionary inside a dictionary which contains a list of tuples into a pandas dataframe如何将包含元组列表的字典中的字典转换为熊猫数据框
【发布时间】:2021-06-01 17:11:57
【问题描述】:

我有一本这样的字典

{
  'S1' :
     {
       'w1':[  ('a',0), ('b',1), ('c',3)],
       'w2':[  ('a',1), ('b',2), ('c',5)], 
       'w3':[  ('a',1), ('b',1), ('c',4)]
     },
 'S2' :      
    {
      'w4':[  ('a',1), ('b',2), ('c',5)],
      'w5':[  ('a',0), ('b',3), ('c',4)], 
      'w6':[  ('a',3), ('b',3), ('c',6)]
    }
}

我想把它转换成这样的熊猫数据框:

有人可以帮我解决这个问题吗?

【问题讨论】:

    标签: pandas list dataframe dictionary tuples


    【解决方案1】:

    对字典列表使用嵌套列表推导和合并字典并传递给DataFrame 构造函数:

    L = [{**{'Col S': k,'Col W':k1}, **dict(v1)} for k, v in d.items() for k1, v1 in v.items()]
    
    df = pd.DataFrame(L)
    print (df)
      Col S Col W  a  b  c
    0    S1    w1  0  1  3
    1    S1    w2  1  2  5
    2    S1    w3  1  1  4
    3    S2    w4  1  2  5
    4    S2    w5  0  3  4
    5    S2    w6  3  3  6
    

    MultiIndex 的解决方案:

    d = {(k, k1): dict(v1) for k, v in d.items() for k1, v1 in v.items()}
    
    df = pd.DataFrame.from_dict(d, orient='index')
    print (df)
           a  b  c
    S1 w1  0  1  3
       w2  1  2  5
       w3  1  1  4
    S2 w4  1  2  5
       w5  0  3  4
       w6  3  3  6
    

    然后设置索引名称并将MultiIndex转换为列,谢谢@sammywemmy:

    df = df.rename_axis(index = ['Col S', 'Col W']).reset_index()
    print (df)
      Col S Col W  a  b  c
    0    S1    w1  0  1  3
    1    S1    w2  1  2  5
    2    S1    w3  1  1  4
    3    S2    w4  1  2  5
    4    S2    w5  0  3  4
    5    S2    w6  3  3  6
    

    【讨论】:

    • 您可以使用rename_axis 扩展第二个答案:df.rename_axis(index = ['Col S', 'Col W']).reset_index()
    • @jezrael,600k+ 恭喜 :)
    • @AkshaySehgal - 谢谢。
    • 这太棒了。非常感谢 Jezrael,Akshay。
    猜你喜欢
    • 1970-01-01
    • 2019-07-18
    • 2017-12-12
    • 2018-11-25
    • 1970-01-01
    • 2016-09-06
    • 2017-07-11
    • 2019-04-21
    • 1970-01-01
    相关资源
    最近更新 更多