[Python] Dropping grouped rows based on a certain hierarchical column

Discussão em 'Python' iniciado por Stack, Abril 20, 2025.

  1. Stack

    Stack Membro Participativo

    Suppose I have this pandas dataset:

    ID Question Code
    1 Q01
    1 Q01-1
    1 Q02
    2 Q01
    2 Q02
    2 Q02-1
    2 Q02-1-1
    2 Q02-2

    I want to remove the rows based on certain hierarchical conditions between the values of question codes per ID. For example, Q01-1 is a sub-question when Q01 is answered, soI don't need to keep Q01 anymore since we already have Q01-1. By ID 2, I need to show Q01, Q02-1-1 (since it is a sub-question of Q02-1, which is also one of Q02) and Q02-2 (since it is also another sub-question of Q02).

    The desired final result of the table above would be:

    ID Question Code
    1 Q01-1
    1 Q02
    2 Q01
    2 Q02-1-1
    2 Q02-2

    Thanks in advance for the help!

    Continue reading...

Compartilhe esta Página