[Python] How to split dataframe into multiple sub-dataframes based on column value

Discussão em 'Python' iniciado por Stack, Novembro 25, 2025.

  1. Stack

    Stack Membro Participativo

    I got a dataframe df1 which looks like this:

    Column1 Column2
    13 1
    12 1
    15 0
    16 0
    15 1
    14 1
    12 1
    11 0
    21 1
    45 1
    44 0

    The 1s indicate that a measurement started, I don't know how many 1s will be in one measurement and also don't know how many 0s will be in between two measurements. So what I want to yield are sub-dataframes, which are as long as I received a 1. So in my example it would be:

    df2

    Column1 Column2
    13 1
    12 1

    df3

    Column1 Column2
    15 1
    14 1
    12 1

    and df4

    Column1 Column2
    21 1
    45 1

    Alternatively, it would be acceptable to count up on Column2, so I can later split based on that value of Column2:

    df5

    Column1 Column2
    13 1
    12 1
    15 0
    16 0
    15 2
    14 2
    12 2
    11 0
    21 3
    45 3
    44 0

    I have no idea on how to approach this. Also with googling I could not find a proper approach. Thanks for any help.

    Continue reading...

Compartilhe esta Página