Python Pandas:如何从嵌套字典中创建列

问题描述 投票:0回答:2

我正试图通过创建单独的列来过滤数据框,以提高可读性和可用性。

问题陈述:列“ Editables”具有一个嵌套的字典,作为我试图根据键创建单独的列的值。例如'photo_repace''text_remove','text_add'具有不同的列。

嵌套字典:

{
'photo': {
    'photo_replace': None,
    'photo_remove': None,
    'photo_add': None,
    'photo_effect': None,
    'photo_brightness': None,
    'background_color': None,
    'photo_resize': None,
    'photo_rotate': None,
    'photo_mirror': None,
    'photo_layer_rearrange': None,
    'photo_move': None
},
'text': {
    'text_remove': None,
    'text_add': None,
    'text_edit': None,
    'font_select': None,
    'text_color': None,
    'text_style': None,
    'background_color': None,
    'text_align': None,
    'text_resize': None,
    'text_rotate': None,
    'text_move': None,
    'text_layer_rearrange': None
}
}

输出

enter image description here

我一直在使用的代码:

df["editables"] = df["editables"].apply(lambda x : dict(eval(x)))
df_edit = df["editables"].apply(pd.Series )

输出:enter image description here

python pandas dataframe jupyter-notebook
2个回答
1
投票

使用每行json.json_normalizejson.json_normalize,最后删除列名中第一个concat之前的值:

concat

1
投票

尝试一下:

.

注意:from pandas.io.json import json_normalize c = ['photo.photo_replace', 'photo.photo_remove', 'text.text_remove'] df = pd.concat([json_normalize(x)[c] for x in df['editables']], ignore_index=True) df.columns = df.columns.str.split('.').str[1] print (df) photo_replace photo_remove text_remove 0 None None None 1 None None None 数据帧。

© www.soinside.com 2019 - 2024. All rights reserved.