[Python] Identify a column cell and perform subtraction with the same column

Discussão em 'Python' iniciado por Stack, Junho 29, 2025.

  1. Stack

    Stack Membro Participativo

    This is just a small example DataFrame, but in reality, I’m working with a much larger and uneven dataset. I need to identify the data in pattern to perform subtraction within the same column. Please take a look at my attempt and the expected result below.

    df = pd.DataFrame([{'col1': "", 'col2': ""}, {'col1': 10.0, 'col2': 'A'}, {'col1': 20.0, 'col2': 'D'}, {'col1': "", 'col2': ""}, {'col1': "", 'col2': ""}, {'col1': "", 'col2': ""}, {'col1': 40.0, 'col2': 'W'}, {'col1': 10.0, 'col2': 'E'}, {'col1': 15.0, 'col2': 'R'}, {'col1': "", 'col2': ""}, {'col1': "", 'col2': ""}, {'col1': 5.0, 'col2': 'F'}, {'col1': 10.0, 'col2': 'H'}, {'col1': 15.0, 'col2': 'U'}, {'col1': 11.0, 'col2': 'T'}])

    print (df)

    col1 col2
    0 NaN NaN
    1 10.0 A
    2 20.0 D
    3 NaN NaN
    4 NaN NaN
    5 NaN NaN
    6 2.0 W
    7 10.0 E
    8 15.0 R
    9 NaN NaN
    10 NaN NaN
    11 5.0 F
    12 10.0 H
    13 9.0 U
    14 11.0 T


    Need to identify the data to perform subtraction as shown below. Additional Column "IdentifySub"

    col1 col2 IdentifySub
    0 NaN NaN NaN
    1 10.0 A 1.0
    2 20.0 D 2.0
    3 NaN NaN NaN
    4 NaN NaN NaN
    5 NaN NaN NaN
    6 2.0 W 1.0
    7 10.0 E 2.0
    8 15.0 R 3.0
    9 NaN NaN NaN
    10 NaN NaN NaN
    11 5.0 F 1.0
    12 10.0 H 2.0
    13 9.0 U 3.0
    14 11.0 T 4.0


    Perform Subtraction from even to odd number only.

    col1 col2 IdentifySub Result
    0 NaN NaN NaN NaN
    1 10.0 A 1.0 NaN
    2 20.0 D 2.0 10.0
    3 NaN NaN NaN NaN
    4 NaN NaN NaN NaN
    5 NaN NaN NaN NaN
    6 2.0 W 1.0 NaN
    7 10.0 E 2.0 8.0
    8 15.0 R 3.0 NaN
    9 NaN NaN NaN NaN
    10 NaN NaN NaN NaN
    11 5.0 F 1.0 NaN
    12 10.0 H 2.0 5.0
    13 9.0 U 3.0 NaN
    14 11.0 T 4.0 2.0

    Continue reading...

Compartilhe esta Página