将嵌套列表和字典转换为数据框?

斯佩多

我有一本具有数千个键的字典,如下所示:

 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.  ..       ..      ..     ..
理查德·余

我为此尝试了一种解决方案,但是它要求每个键(即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)

这是输出:

在此处输入图片说明

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章