python - How can I create columns out of a nested dictionary in python pandas
问题描述
I'm trying to filter my data frame by making separate columns to increase readability and usability.
Problem statement: Column "Editables" has a nested dictionary as the value I'm trying to create separate columns as per the key. For instance 'photo_repace' 'text_remove', 'text_add' has different columns.
The nested dictionary:
{
'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
}
}
Output
Code I've been using:
df["editables"] = df["editables"].apply(lambda x : dict(eval(x)))
df_edit = df["editables"].apply(pd.Series )
解决方案
Try this:
>>> dct = {
'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
}
}
>>> pd.DataFrame(dct).T
photo_replace photo_remove ... text_move text_layer_rearrange
photo NaN NaN ... NaN NaN
text NaN NaN ... NaN NaN
[2 rows x 22 columns]
>>> pd.DataFrame(dct).T[['photo_replace', 'photo_remove', 'text_remove']]
photo_replace photo_remove text_remove
photo NaN NaN NaN
text NaN NaN NaN
NOTE: .T
transposes the dataframe.
推荐阅读
- c# - C# Windows 资源管理器文件预览
- javascript - Visual Studio Code - JavaScript - Intellisense 无法正常工作
- flutter - 错误状态:试图读取在创建其值期间抛出的提供程序
- r - CentOS 安装 R 包 RLumShiny 失败
- c++ - 解析字符串以创建几何图形
- node.js - 从 Nodejs 发送的错误请求错误 - 原始消息缺少标头信息
- sql - Oracle 将今天的值传递给变量并使用它
- mongodb - 彼此相邻的数字相加(例如 123 + 123 = 123123)
- rasa - AttributeError:模块“pyparsing”没有属性“downcaseTokens”rasa
- spring - Spring Transactions - 交易超时:截止日期为 Thu Oct 28 22:23:09 SGT 2021