在Python中将数据框转换为嵌套字典 [英] Convert Dataframe to Nested Dictionary in Python

查看:381
本文介绍了在Python中将数据框转换为嵌套字典的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找一种将数据框转换为字典的方法,与此处的要求非常相似:

I’m looking for a way to convert a dataframe into a dictionary, very similar to what has been asked here:

将pandas DataFrame转换为嵌套的dict

假定为示例数据帧

name    v1  v2  v3
0        A  A1  A11 1
1        A  A2  A12 2
2        B  B1  B12 3
3        C  C1  C11 4
4        A  A2  A21 6
5        A  A2  A21 8

列数可能会有所不同,列名也可能会有所不同。

The number of columns may differ and so does the column names.

我要生成:

{
    'A' : { 
        'A1' : { 'A11' : 1 },
        'A2' : { 'A12' : 2 , 'A21' : 6 , 'A21' : 8 },
        'B1' : {}, 
        'C1' : {}
    }, 

    'B' : { 
        'A1' : {},
        'A2' : {},
        'B1' : { 'B12' : 3}, 
        'C1' : {}
    },

    'C' : { 
        'A1' : {},
        'A2' : {},
        'B1' : {} ,
        'C1' : { 'C11' : 4}
    }

}

其他地方建议的方法是通过递归:

The method suggested elsewhere is via recursion:

def recur_dictify(frame):
    if len(frame.columns) == 1:
        if frame.values.size == 1: return frame.values[0][0]
        return frame.values.squeeze()
    grouped = frame.groupby(frame.columns[0])
    d = {k: recur_dictify(g.ix[:,1:]) for k,g in grouped}
    return d

/ p>

Which gives:

>>> pprint.pprint(recur_dictify(df))
{'A': {'A1': {'A11': 1}, 'A2': {'A12': 2, 'A21': [6,8]}},
 'B': {'B1': {'B12': 3}},
 'C': {'C1': {'C11': 4}}}

但是不要在v2级别复制空字典巢,而是将A2 -A21的重复分组为array [6,8 ]。我看过将Pandas DataFrame转换成字典,没有

But doesn’t replicate the empty dict nest at level v2 , and groups the repetition of A2 -A21 into array[6,8] . I’ve looked at Convert a Pandas DataFrame to a dictionary, no luck so far.

推荐答案

我认为:


  • 索引没有名称

  • 列名称具有值A,B,C,D

  • 等。

和df包含上述recur_dictify的输出:

and df contains the output of your recur_dictify above:

ky = frame.v1.unique() # I assume it's ['A1','B1','C1']

for k in df:
    for l in ky:
        if l not in df[k]:
            df[k][l] = {}

您的原始数据帧很奇怪。 B2条目不会出现在结果中的任何地方。

You original dataframe is strange though. The B2 entry does not appear anywhere in your result.

这篇关于在Python中将数据框转换为嵌套字典的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆