[Python] Assign column status retrospectively in pandas

Discussão em 'Python' iniciado por Stack, Julho 26, 2025.

  1. Stack

    Stack Membro Participativo

    I have created the following pandas dataframe:

    import pandas as pd
    import numpy as np

    ds = {'col1' : [234,321,284,286,287,300,301,303,305,299,288,300,299,287,286,280,279,270,269,301]}

    df = pd.DataFrame(data=ds)


    The dataframe looks like this:

    display(df)

    col1
    0 234
    1 321
    2 284
    3 286
    4 287
    5 300
    6 301
    7 303
    8 305
    9 299
    10 288
    11 300
    12 299
    13 287
    14 286
    15 280
    16 279
    17 270
    18 269
    19 301


    I have then created two columns (cnsIncr , cnsDecr), which calculate the consecutive increase and decrease in col1 respectively.

    cnsIncr = []
    cnsDecr = []

    col1 = np.array(df['col1'])

    for i in range(len(df)):
    cnsIncr.append(0)
    cnsDecr.append(0)
    if(col1 > col1[i-1]):
    cnsIncr = cnsIncr[i-1]+1
    else:
    cnsIncr = 0

    if(col1 < col1[i-1]):
    cnsDecr = cnsDecr[i-1]+1
    else:
    cnsDecr = 0

    df['cnsIncr'] = cnsIncr
    df['cnsDecr'] = cnsDecr


    The resulting dataframe looks as follows:

    [​IMG]

    I need to create a columns called Trend which is populated as follows:

    • if the column cnsIncr contains a value greater or equal to 5, then Trend = UpTrend starting from the record in which consIncr = 0 and ending at the record for which cnsIncr >= 5;
    • if the column cnsDecr contains a value greater or equal to 5, then Trend = DownTrend starting from the record in which cnsDecr = 0 and ending at the record for which cnsDecr >= 5;
    • the neither the column cnsIncr nor the column cnsDecr contain a value of 5, then Trend = NoTrend

    So, from the example above, the resulting dataframe would look like this:

    [​IMG]

    How can I do this?

    Continue reading...

Compartilhe esta Página