如何将含列表的嵌套字典转换为Pandas DataFrame?
嵌套字典转Pandas DataFrame:将action_type转为列的解决方案
给定如下嵌套字典,需要将其转换为Pandas DataFrame,要求每个action_type作为列,对应的value作为行值,缺失的action_type对应行填充N/A:
test = {'data': [ {'actions': [ {'action_type': 'link_click', 'value': '16'}, {'action_type': 'post_engagement', 'value': '16'}, {'action_type': 'page_engagement', 'value': '16'}], 'spend': '13.59', 'date_start': '2023-02-07', 'date_stop': '2023-02-07'}, {'actions': [ {'action_type': 'comment', 'value': '5'}, {'action_type': 'onsite_conversion.post_save', 'value': '1'}, {'action_type': 'link_click', 'value': '465'}, {'action_type': 'post', 'value': '1'}, {'action_type': 'post_reaction', 'value': '20'}, {'action_type': 'video_view', 'value': '4462'}, {'action_type': 'post_engagement', 'value': '4954'}, {'action_type': 'page_engagement', 'value': '4954'}], 'spend': '214.71', 'date_start': '2023-02-07', 'date_stop': '2023-02-07'}]}
处理步骤与代码
核心思路是先把每个数据项里的actions列表转换成字典,再和其他字段合并,最后利用Pandas自动补全缺失列:
import pandas as pd # 遍历处理每个数据条目 processed_items = [] for entry in test['data']: # 将actions列表转成{action_type: value}的键值对 action_map = {act['action_type']: act['value'] for act in entry['actions']} # 合并当前条目的其他字段(spend、日期)和action_map combined = {**entry, **action_map} # 删除原有的actions字段,避免冗余 del combined['actions'] processed_items.append(combined) # 转换为DataFrame,缺失的列自动填充NaN(即N/A) result_df = pd.DataFrame(processed_items) # 可选优化:将数值类字段转为合适的数据类型 result_df['spend'] = result_df['spend'].astype(float) # 遍历所有action类型的列,转为数值型 for col in result_df.columns.drop(['spend', 'date_start', 'date_stop']): result_df[col] = result_df[col].astype(float) # 查看结果 print(result_df)
结果说明
转换后的DataFrame会包含所有出现过的action_type作为列,比如第一条数据没有的comment、video_view等列会自动填充NaN;同时完整保留原有的spend、date_start、date_stop字段。
内容的提问来源于stack exchange,提问作者griefter
相关产品推荐
相关产品推荐

