Skip to content Skip to sidebar Skip to footer

Loop Logic To Calculate % Change

My dataframe: A B C A_Q B_Q C_Q 27 40 41 2 1 etc 28 39 40 1 5 30 28 29 3 6 28 27 28 4 1 15 10 11 5 4 17 13

Solution 1:

Do you need to append the results as a new column? You're going to end up with nearly empty columns with just one data value. Could you just append all of the results at the bottom of the '_Q' columns? Anyway here's my stab at the function to do all you asked:

deffunc(col1, col2):
    l = []
    x = Nonefor index inrange(0, len(col1)):
        if x isNoneand col1[index] == 1:
            x = col2[index]
            l.append(0)
        elifnot(x isNone) and col1[index] == 10:
            y = col2[index]
            l.append(((float(y)/x)-1)*100)
            x = Noneelse:
            l.append(0)
    return l

You'd then pass this function A_Q as col1 and A as col2 and it should return what you want. For passing functions, assuming that every A, B, C column has an associated _Q column, you could do something like:

q = [col forcolin df.columns if'_Q' in col]
forcolin q:
    df[col[:len(col) - 2] + '_S] = func(df[col], df[col[:len(col) - 2]

Post a Comment for "Loop Logic To Calculate % Change"