如何将DataFrame中含JSON内容的maplist列拆分为两列并按产品生成对应行
实现方案
核心思路:先将maplist列的非标准类JSON字符串转换为Python字典列表,再通过行展开、字段提取两步得到目标结果。
前置依赖
需提前安装pandas库,内置的ast模块无需额外安装。
import pandas as pd import ast
步骤1:处理maplist列格式
maplist列当前是不符合JSON规范的字符串,需要先转成可操作的字典列表:
def parse_maplist(s): # 处理空数组的情况 if not s or s.strip() == '[]': return [] # 替换非标准格式为可解析格式 s = s.replace('=', ':') s = s.replace('share', '"share"').replace('product', '"product"') s = s.replace('N', '"N"').replace('Y', '"Y"') return ast.literal_eval(s) # 应用转换到maplist列 df['maplist'] = df['maplist'].apply(parse_maplist)
注:如果你的
maplist列加载后已经是列表类型而非字符串,可直接跳过这一步。
步骤2:按product条目拆分为多行
用pandas的explode方法将数组中的每个字典拆为独立行:
# 拆分为多行,低版本pandas可以用 df.explode('maplist').reset_index(drop=True) 替代 df_exploded = df.explode('maplist', ignore_index=True)
步骤3:提取share和product独立列
从每行的字典中提取对应字段生成新列:
# 提取字段,自动处理空值(对应原maplist为空数组的行) df_exploded['share'] = df_exploded['maplist'].apply(lambda x: x.get('share') if isinstance(x, dict) else None) df_exploded['product'] = df_exploded['maplist'].apply(lambda x: x.get('product').strip() if isinstance(x, dict) else None) # 可选:删除不再需要的maplist列得到最终结果 df_final = df_exploded.drop('maplist', axis=1)
效果验证
以上代码执行后,df_final的结构完全符合预期输出:
- Asma Khan对应2行数据,分别对应Banana和Books两个product
- Ravi kumar对应3行数据,包含Washroom条目
- Sharukh Khan对应1行,share和product列为空值
内容的提问来源于stack exchange,提问作者mr.data_engg
相关产品推荐
相关产品推荐

