【问题标题】:How to Convert a dataframe into nested dictionary in the following format如何将数据框转换为以下格式的嵌套字典
【发布时间】:2020-09-03 09:20:31
【问题描述】:
   2  3  4  loc_id 
0  b  b  c       1            
1  b  b  c       6            
2  b  a  b       8            
3  b  b  c      10            
4  b  a  b      11            

somone 可以帮我将上述数据框转换为 Python 中的以下字典,其中列名作为第一个键,其中的字典将键作为某些列的列值,将值作为另一列的列值 em>

{2:{'b':[1,6,8,10,11]},3:{'b':[1,6,10],'a':[8,11]},4:{'c':[1,6,10],'b':[8,11]}}

【问题讨论】:

  • 请不要发布代码或数据帧的图像,分享实际的数据帧以便我们复制/粘贴它
  • 那么你的问题是什么? SO不是代码服务网站...

标签: python pandas dictionary


【解决方案1】:

使用DataFrame.meltGroupBy.agg 并列出MultiIndex Series,然后创建嵌套字典:

s = df.melt('loc_id').groupby(['variable','value'])['loc_id'].agg(list)

d = {level: s.xs(level).to_dict() for level in s.index.levels[0]}
print (d)
{'2': {'b': [1, 1, 6, 8, 10, 11]}, 
 '3': {'a': [8, 11], 'b': [1, 1, 6, 10]}, 
 '4': {'b': [8, 11], 'c': [1, 1, 6, 10]}}

或创建Series 的字典并聚合索引到列表:

d = {k: v.groupby(v).agg(lambda x: list(x.index)).to_dict() 
     for k, v in df.set_index('loc_id').to_dict('series').items()}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-08-30
    • 2019-09-06
    • 2017-09-04
    • 2014-05-10
    • 1970-01-01
    • 2021-11-28
    相关资源
    最近更新 更多