数据帧:
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的方式,请让我知道如何使用熊猫
所需输出:
[{
"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"
}
]
}
]
list
个dicts
李>g
是tuple
表示用于分组的值d
是groupby值的数据帧,g
_
表示的index
,因为不需要它data
,从中删除groupby_list
中的标签,然后使用^{dict
,并将其附加到list
,att_list
att_list
作为值分配给group['attributes']
dict
、group
附加到dict_list
李>dict_list
可以通过以下方式转换回数据帧:df = pd.json_normalize(dict_list, 'attributes', meta=groupby_list)
dict_list
:相关问题 更多 >
编程相关推荐