使用 pandas groupby 转换唯一值
transform unique values using pandas groupby
我有这样的输入字典:
{
"objects": [
{
"objType": "master",
"objName": "sampleOne",
"objTitle": "Sample One"
},
{
"objType": "master",
"objName": "sampleTwo",
"objTitle": "Sample Two"
},
]
}
我想将键 objType
的相同值分组以生成如下的字典
{
"objects": [
{
"objType": "master",
"objDetails": [
{
"objName": "sampleOne",
"ObjectTitle": "Sample One"
},
{
"objName": "sampleTwo",
"ObjectTitle": "Sample Two"
}
]
]
}
我已经使用 pandas groupby 但无法获得所需的输出。
考虑到您的数据的多层结构,我不确定 pandas 是否适合您要完成的任务。以下函数将根据您的示例输入和所需输出正确解析您的数据。
def transform(di):
tmp = dict()
for ntry in di['objects']:
tval = tmp.pop(ntry['objType'], [])
indict = dict()
indict['objName'] = ntry['objName']
indict['ObjectTitle'] = ntry['objTitle']
tval.append(indict)
tmp[ntry['objType']] = tval
return {'objects': tmp}
给定输入
di = {
"objects": [
{
"objType": "master",
"objName": "sampleOne",
"objTitle": "Sample One"
},
{
"objType": "master",
"objName": "sampleTwo",
"objTitle": "Sample Two"
}
]
}
transform(di)
产生:
{'objects':
{'master': [{'objName': 'sampleOne', 'ObjectTitle': 'Sample One'},
{'objName': 'sampleTwo', 'ObjectTitle': 'Sample Two'}]}}
我有这样的输入字典:
{
"objects": [
{
"objType": "master",
"objName": "sampleOne",
"objTitle": "Sample One"
},
{
"objType": "master",
"objName": "sampleTwo",
"objTitle": "Sample Two"
},
]
}
我想将键 objType
的相同值分组以生成如下的字典
{
"objects": [
{
"objType": "master",
"objDetails": [
{
"objName": "sampleOne",
"ObjectTitle": "Sample One"
},
{
"objName": "sampleTwo",
"ObjectTitle": "Sample Two"
}
]
]
}
我已经使用 pandas groupby 但无法获得所需的输出。
考虑到您的数据的多层结构,我不确定 pandas 是否适合您要完成的任务。以下函数将根据您的示例输入和所需输出正确解析您的数据。
def transform(di):
tmp = dict()
for ntry in di['objects']:
tval = tmp.pop(ntry['objType'], [])
indict = dict()
indict['objName'] = ntry['objName']
indict['ObjectTitle'] = ntry['objTitle']
tval.append(indict)
tmp[ntry['objType']] = tval
return {'objects': tmp}
给定输入
di = {
"objects": [
{
"objType": "master",
"objName": "sampleOne",
"objTitle": "Sample One"
},
{
"objType": "master",
"objName": "sampleTwo",
"objTitle": "Sample Two"
}
]
}
transform(di)
产生:
{'objects':
{'master': [{'objName': 'sampleOne', 'ObjectTitle': 'Sample One'},
{'objName': 'sampleTwo', 'ObjectTitle': 'Sample Two'}]}}