[Python] How to get parent hierarchy from another dataframe in Python?

Discussão em 'Python' iniciado por Stack, Fevereiro 10, 2025.

  1. Stack

    Stack Membro Participativo

    I have a dataframe of ANZSIC Codes named df_anzsiccode which has the following fields -

    • anzsiccodeid - UUID
    • name - ANZSIC Title
    • anzsictype - Categorical value whether it's Division, Sub-division, Group or Class
    • code - ANZSIC Code
    • parentanzsiccode - tells the anzsiccodeid of it's parent in the heirarchy
    • anzsiccodestringlength - gives the length of the code

    The length of the code has significance in the fact that each heirarchy level is a different string length, i.e. Division - 1, SubDivision is 2, Group is 3 and Class is 4. The ANZSIC codes follow the heirarchy of Division --> Sub Division --> Group --> Class.

    Some sample rows of this table are as follows - [​IMG]

    In my other dataframe df_facility I'm given the anzsiccode and anzsictitle that relates to code and name in the anzsiccode dataframe.

    How can I get the ANZSIC codes (code) and Titles (name) from df_anzsiccode for all the parent elements (going up from whichever level it is at) into new columns ClassName, GroupName, SubDivisionName and DivisionName fields in the df_facility dataframe?

    For eg. if df_facility lists the anzsiccodeid of a Group, then I would want the GroupName, SubDivisionName and DivisionName populated and the ClassName be left NULL in separate columns in the df_facility. Similarly, if df_facility lists the anzsiccodeid of a SubDivision, then I would want the SubDivisionName and DivisionName populated and the GroupName and ClassName be left as NULL in respective columns of the dataframe.

    The expected output is - [​IMG]

    How can I accomplish this in Python?

    Continue reading...

Compartilhe esta Página