[Python] Creating new rows in a dataframe based on previous values

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

  1. Stack

    Stack Membro Participativo

    I have a dataframe that looks like this:

    test = pd.DataFrame(
    {'onset': [1,3,18,33,35,50],
    'duration': [2,15,15,2,15,15],
    'type': ['Instr', 'Remember', 'SocTestString', 'Rating', 'SelfTestString', 'XXX']
    }
    )


    I want to create a new dataframe such that when type contains "TestString",

    • two new rows are created below that row, such that the row is is now split into three rows with (for example) SocTestString_1, SocTestString_2, SocTestString_3
    • for those three rows, change duration columns to the value 5
    • for those three rows, also change the onset column such that it is the onset value of the previous column + 5

    The final dataframe should look like this:

    test_final = pd.DataFrame(
    {'onset': [1,3,18,23,28,33,35,40,45,50],
    'duration': [2,15,5,5,5,2,5,5,5,15],
    'type': ['Instr', 'Remember', 'SocTestString_1', 'SocTestString_2', 'SocTestString_3', 'Rating', 'SelfTestString_1', 'SelfTestString_2', 'SelfTestString_3', 'XXX']
    })


    How may I accomplish this?

    Continue reading...

Compartilhe esta Página