0

数据框

df = {"UNIT":["UNIT1","UNIT1","UNIT2","UNIT2"],
"PROJECT":["A","A","C","C"],
"TEAM":[1,2,1,2],
"NAME":["FANNY", "KATY", "PERCY", "PETER"],
"ID":[123,234,333,222]}
data = pd.DataFrame(df)

    UNIT PROJECT  TEAM   NAME   ID
0  UNIT1       A     1  FANNY  123
1  UNIT1       A     2   KATY  234
2  UNIT2       C     1  PERCY  333
3  UNIT2       C     2  PETER  222

预期产出

[
    {
        "UNIT": "UNIT1",
        "PROJECT": "A",
        "TEAM_DETAIL": [
            {
                "TEAM": 1,
                "MEMBER": [
                    {
                        "NAME": "FANNY",
                        "ID": 123
                    }
                ]
            },
            {
                "TEAM": "TEAM 2",
                "MEMBER": [
                    {
                        "NAME": "KATY",
                        "ID": 234
                    }
                ]
            }
        ]
    },
    {
        "UNIT": "UNIT2",
        "PROJECT": "C",
        "TEAM_DETAIL": [
            {
                "TEAM": 1,
                "MEMBER": [
                    {
                        "NAME": "PERCY",
                        "ID": 333
                    }
                ]
            },
            {
                "TEAM": "TEAM 2",
                "MEMBER": [
                    {
                        "NAME": "PETER",
                        "ID": 222
                    }
                ]
            }
        ]
    }
]

在这种情况下,我想对数据进行分组TEAM,从而显示每个团队中的每个成员详细信息。无需添加自定义标签,例如。TEAM_DETAIL并且MEMBER,可以通过使用轻松实现.to_dict() 但是,我不知道如何在每个级别上添加标签。

4

1 回答 1

1

您必须MEMBER使用第一个groupby. 然后你可以用一秒钟groupby来创建TEAM_DETAIL列表。

完整代码:

import pandas as pd

data = {"UNIT":["UNIT1","UNIT1","UNIT2","UNIT2"],
"PROJECT":["A","A","C","C"],
"TEAM":[1,2,1,2],
"NAME":["FANNY", "KATY", "PERCY", "PETER"],
"ID":[123,234,333,222]}
df = pd.DataFrame(data)
df

json = (df.groupby(['UNIT','PROJECT', 'TEAM'])
       .apply(lambda x: x[['NAME','ID']].to_dict('records'))
       .reset_index()
       .rename(columns={0:'MEMBER'})
       .groupby(['UNIT','PROJECT'])
       .apply(lambda x: x[['TEAM','MEMBER']].to_dict('records'))
       .reset_index()
       .rename(columns={0:'TEAM_DETAIL'})
       .to_json(orient='records'))
     
print(json)

输出:

'[{"UNIT":"UNIT1","PROJECT":"A","TEAM_DETAIL":[{"TEAM":1,"MEMBER":[{"NAME":"FANNY","ID":123}]},{"TEAM":2,"MEMBER":[{"NAME":"KATY","ID":234}]}]},{"UNIT":"UNIT2","PROJECT":"C","TEAM_DETAIL":[{"TEAM":1,"MEMBER":[{"NAME":"PERCY","ID":333}]},{"TEAM":2,"MEMBER":[{"NAME":"PETER","ID":222}]}]}]'
于 2022-01-24T15:49:19.093 回答