【问题标题】:Converting nested lists and dictionary to Dataframe?将嵌套列表和字典转换为 Dataframe?
【发布时间】:2019-05-07 16:22:03
【问题描述】:

我有一本包含千键的字典,如下所示:

 my_dictionary:
                {'key1':[['ft1',[2,4,12,2]],['ft2',[0,3,3,1]],'key2':[['ft1',[5,0,2,9]],['ft2',[10,39,3,2]]}

现在,我想将此字典转换为数据框,其中键应该是特定列,并且特征(ft1、ft2、..)及其值也转换为不同的列。所以我想要的数据框应该是这样的:

 my_new_dataframe:
             ID, ft1_sig,ft1_med,ft1_les,ft1_non,ft2_sig,ft2_med,ft2_les,ft2_non,... 
             key1    2       4      12      2       0       3       3.     1
             key2    5.      0.      2.     9.      10.     39     3.     2
             ...
             keyn.  ..       ..      ..     ..

【问题讨论】:

    标签: python dataframe dictionary data-conversion


    【解决方案1】:

    我尝试了一个解决方案,但它要求每个键(即 key1、key2 等)都包含您想要在字典中的 ft 属性。另外,您是否缺少原始列表的“]”?当我粘贴到我的解释器中时,它不匹配。

    import pandas as pd
    
    #added method to change your original dictionary to one that I can manipulate with the method below.
    
    #If you compare the values of new_dict and data using ==, it returns true.
    my_dictionary = {'key1':[['ft1',[2,4,12,2]],['ft2',[0,3,3,1]]],'key2':[['ft1',[5,0,2,9]],['ft2',[10,39,3,2]]]}
    
    new_dict ={}
    for element in my_dictionary:
        print(element)
        print(my_dictionary[element])
        new_dict[element] = dict(my_dictionary[element])
        print(new_dict)
    
    data = {
        'key1':{
            'ft1':[2,4,12,2],
            'ft2':[0,3,3,1]
            },
        'key2':{
            'ft1':[5,0,2,9],
            'ft2':[10,39,3,2]
            }
        }
    
    keys = list(data.keys())
    
    df = pd.DataFrame.from_dict(data).T
    
    df2 = pd.DataFrame(df.ft1.values.tolist()).add_prefix('ft1_')
    df3 = pd.DataFrame(df.ft2.values.tolist()).add_prefix('ft2_')
    df4 = pd.merge(df2,df3,left_index=True,right_index=True)
    df4.index=keys
    
    print(df4)
    

    这是输出:

    【讨论】:

      【解决方案2】:

      我在您的示例中添加了更多数据,以表明如果添加了新功能或行(键),脚本将是灵活的。

      • 收集列表中的所有特征(列名)
      • 只获取号码列表
      • 分配新的列名
      • 创建一个函数,返回数字列表中的每个项目
      • 使用 apply 函数创建新列
      • 删除/删除临时列

      在这里

      mydict = {'key1':[['ft1',[2,4,12,2]],['ft2',[0,3,3,1]],['ft3',[0,3,3,1]]],
                'key2':[['ft1',[5,0,2,9]],['ft2',[10,39,3,2]],['ft3',[0,3,3,1]]]
               ,'key3':[['ft1',[5,0,2,9]],['ft2',[10,39,3,2]],['ft3',[0,3,3,1]]]} 
      df = pd.DataFrame(mydict).T 
      colname = [df[c][0][0] for c in df]
      df = df.applymap(lambda c: c[1])
      df.reset_index(level=0, inplace=True)
      df.columns=['ID'] + colname
      s=['_sig','_med','_les','_non']
      def f(x):
          return pd.Series([x[0], x[1], x[2], x[3]])
      for col in colname:
          df[[col+'_sig', col+'_med', col+'_les', col+'_non']]= df[col].apply(lambda x: f(x))
      df.drop(colname, axis=1, inplace=True)
      df
      

      结果:

           ID ft1_sig ft1_med ft1_les ft1_non ft2_sig ft2_med ft2_les ft2_non ft3_sig ft3_med ft3_les ft3_non
      0   key1    2    4  12  2    0   3  3   1   0   3   3   1
      1   key2    5    0   2  9   10  39  3   2   0   3   3   1
      2   key3    5    0   2  9   10  39  3   2   0   3   3   1
      

      【讨论】:

        猜你喜欢
        • 2018-10-26
        • 1970-01-01
        • 2019-05-27
        • 1970-01-01
        • 2013-11-16
        • 2019-04-08
        • 2023-02-10
        • 2020-09-03
        相关资源
        最近更新 更多