如何用Pandas递归.groupby实现三层嵌套字典(含列表)结构
解决方案
核心实现代码
import pandas as pd # 构造示例数据集 df = pd.DataFrame({ 'image': ['img1', 'img1', 'img1', 'img2', 'img2', 'img2', 'img2'], 'namespace': ['ns1', 'ns1', 'ns2', 'ns2', 'ns2', 'ns2', 'ns4'], 'key': ['organism', 'organ', 'microscope', 'microscope', 'technique', 'technique', 'analysis'], 'value': ['human', 'liver', 'confocal', 'confocal', 'widefield', 'phase-contrast', 'segmentation'] }) # 三层嵌套字典转换逻辑 result = ( # 按三级维度分组,将每组的value转为列表 df.groupby(['image', 'namespace', 'key'])['value'] .apply(list) # 将key从行索引转为列,实现namespace到key的映射 .unstack('key') # 按image分组,将每个image对应的namespace集合转为字典 .groupby('image') .apply(lambda x: x.to_dict('index')) # 最终转为最外层以image为键的字典 .to_dict() ) print(result)
代码逻辑说明
- 三级分组聚合:通过
groupby(['image', 'namespace', 'key'])锁定三层维度,用apply(list)将每个key对应的所有value打包成列表,满足多value场景需求。 - 索引转列:
unstack('key')把内层的key从行索引移到列位置,让每个namespace下直接对应所有key-value列表的结构。 - 逐层嵌套字典:再次按
image分组后,用to_dict('index')把每个image对应的namespace集合转为字典,最后再转成最外层的image-key字典,完美匹配需求的三层嵌套结构。
输出结果
{"img1": {"ns1": {"organism": ["human"], "organ": ["liver"]}, "ns2": {"microscope": ["confocal"]}}, "img2": {"ns2": {"microscope": ["confocal"], "technique": ["widefield", "phase-contrast"]}, "ns4": {"analysis": ["segmentation"]}}}
内容的提问来源于stack exchange,提问作者Jens Wendt
相关产品推荐
相关产品推荐

