首页 > 解决方案 > 使用两列中的元组样式键将数据框转换为嵌套自定义字典的最 Pythonic 方法

问题描述

我有以下数据框:

import pandas as pd

df = pd.DataFrame({
        "color": ["blue", "blue", "blue", "blue", "green", "green", "green", "green"],
        "object": ["hat", "hat", "coat", "coat", "hat", "hat", "coat", "coat"],
        "group": [1, 2, 1, 2, 1, 2, 1, 2],
        "value": [1.2 , 3.5, 5.4, 7.1, 6.4, 1.8, 3.5, 5.6]
    })

看起来像这样:

在此处输入图像描述

我想创建一个嵌套字典,将列“颜色”和“对象”作为字符串的第一个键(例如"(blue, hat)"注意:这是一个语法不正确的元组。它应该是字符串格式!),组作为第二级的键,值作为第二级的键。即我想要的输出是:

{
    "(blue, hat)": {
        1: 1.2,
        2: 3.5
    },
    "(blue, coat)": {
        1: 5.4,
        2: 7.1
    },
    "(green, hat)": {
        1: 6.4,
        2: 1.8
    },
    "(green, coat)": {
        1: 3.5,
        2: 5.6
    }
}

我的方法是遍历 和 的唯一值,color但这对我来说似乎很麻烦。有没有更蟒蛇的方法?objectgroup

标签: pythonpython-3.xpandasdataframedictionary

解决方案


使用字典DataFrame.groupby推导,如果需要像字符串一样的元组rept,请使用:

d = {str(k): v.set_index('group')['value'].to_dict() 
              for k, v in df.groupby(['color','object'])}
print (d)

  {
    "('blue', 'coat')": {
        1: 5.4,
        2: 7.1
    },
    "('blue', 'hat')": {
        1: 1.2,
        2: 3.5
    },
    "('green', 'coat')": {
        1: 3.5,
        2: 5.6
    },
    "('green', 'hat')": {
        1: 6.4,
        2: 1.8
    }

或者如果需要像'tuple's 一样改变格式而不''使用f-strings:

d = {f'({k[0]}, {k[1]})': v.set_index('group')['value'].to_dict() 
                 for k, v in df.groupby(['color','object'])}

替代join

d = {f'({", ".join(k)})': v.set_index('group')['value'].to_dict() 
                 for k, v in df.groupby(['color','object'])}

print (d)

{
    '(blue, coat)': {
        1: 5.4,
        2: 7.1
    },
    '(blue, hat)': {
        1: 1.2,
        2: 3.5
    },
    '(green, coat)': {
        1: 3.5,
        2: 5.6
    },
    '(green, hat)': {
        1: 6.4,
        2: 1.8
    }
}

推荐阅读