0

数据框:

id      id_2    salary  title   allowance   name
0420    13.28   100000  director    No      Tom
0420    13.28   70000   developer   Yes     Sam
0110    13.12   120000  director    No      Dave
0110    13.12   75000   developer   Yes     shaun 

Groupby id 和 id_2 并将其余列转换为带有列标题的dict

我为此写了一个循环,我认为这不是 python 方式,请让我知道如何使用 pandas 来实现。

所需输出:

[{
            "id": 420,
            "id_2": 13.28,
            "attributes":[
                    {   "salary": 100000,
                        "title":"director",
                        "allowance":"No",
                        "name": "Tom"
                    },
                    {   "salary": 70000,
                        "title": "developer",
                        "allowance":"Yes",
                        "name": "Sam"
                    }
                ]
            },
            {
            "id": 110,
            "id_2": 13.12,
            "attributes":[
                    {   "salary": 120000,
                        "title":"director",
                        "allowance":"No",
                        "name": "Dave"
                    },
                    {   "salary": 75000,
                        "title": "developer",
                        "allowance":"Yes",
                        "name": "shaun"
                    }
                ]
            }   
]
4

1 回答 1

1
  • 没有一个单行 pandas 参数可以提供您要求的形状的 a listof 。dicts
  • 用于.groupby选择组
    • gtuple表示用于 groupby 的值
    • d是 groupby 值的数据框,g
  • 用于.iterrows遍历每组的行
    • 返回index由 first 表示_,因为它不是必需的
    • 返回data,从中groupby_list删除标签,然后将剩余部分转换为dictusing .to_dict(),并将其附加到list,att_list
    • 遍历组的所有行后,将att_list值分配给group['attributes']
  • 遍历每个组后,将dict, , 附加groupdict_list.
  • dict_list可以使用以下内容转换回数据框:
    • df = pd.json_normalize(dict_list, 'attributes', meta=groupby_list)
dict_list = list()
groupby_list = ['id', 'id_2']
for g, d in df.groupby(groupby_list):
    group = dict(zip(groupby_list, g))
    att_list = list()
    for _, data in d.iterrows():
        data = data.drop(labels=groupby_list)
        att_list.append(data.to_dict())
    group['attributes'] = att_list
    dict_list.append(group)

dict_list

[{'attributes': [{'allowance': 'No',
                  'name': 'Dave',
                  'salary': 120000,
                  'title': 'director'},
                 {'allowance': 'Yes',
                  'name': 'shaun',
                  'salary': 75000,
                  'title': 'developer'}],
  'id': 110,
  'id_2': 13.12},
 {'attributes': [{'allowance': 'No',
                  'name': 'Tom',
                  'salary': 100000,
                  'title': 'director'},
                 {'allowance': 'Yes',
                  'name': 'Sam',
                  'salary': 70000,
                  'title': 'developer'}],
  'id': 420,
  'id_2': 13.28}]
于 2020-07-31T22:14:45.307 回答