[Python] Groupby a df column based on more than 3 columns

Discussão em 'Python' iniciado por Stack, Dezembro 18, 2024.

  1. Stack

    Stack Membro Participativo

    I have an df which has 3 columns lets say Region, Country and AREA_CODE.

    Region Country AREA_CODE AREA_SUB_CODE_1 AREA_SUB_CODE_2
    ===========================================================================
    AMER US A1 A1_US_1 A1_US_2
    AMER CANADA A1 A1_CA_1 A1_CA_2
    AMER US B1 B1_US_1 B1_US_2
    AMER US A1 A1_US_1 A1_US_2


    Is there a way to get output list of both the AREA_SUB_CODE_1 and AREA_SUB_CODE_2 as a list under each of the previous column value. something like the below

    {
    "AREA_SUB_CODE_1": {
    "AMER": {
    "US": {
    "A1": ["A1_US_1"],
    "B1": ["B1_US_1"]
    },
    "CANADA": {
    "A1": ["A1_CA_1"],
    }
    }
    },
    "AREA_SUB_CODE_2": {
    "AMER": {
    "US": {
    "A1": {
    "A1_US_1": ["A1_US_2"]
    },
    "B1": {
    "B1_US_1": ["B1_US_2"]
    },
    "CANADA": {
    "A1": {
    "A1_CA_1": ["A1_CA_2"],
    }
    }
    }
    },
    }


    So far i have tried to groupby on 3 columns it works which is,

    for (k1, k2), v in df.groupby(['Region', 'Country'])['AREA_CODE']:
    tTmp.setdefault(k1, {})[k2] = sorted(v.unique())



    But when i try to groupby 4 columns, it is throwing error too many values to unpack (expected 2)

    for (k1, k2), v in df.groupby(['Region', 'Country', 'AREA_CODE'])['AREA_SUB_CODE_1']:
    tTmp.setdefault(k1, {})[k2] = sorted(v.unique())


    Kindly suggest me a way on how to apply groupby for 4 columns and 5 columns. Or any other way to achieve this.

    Thanks in advance.

    Continue reading...

Compartilhe esta Página