[Python] Should we pre-calculate scalar calculations before we apply them to dataframe columns?

Discussão em 'Python' iniciado por Stack, Fevereiro 14, 2025.

  1. Stack

    Stack Membro Participativo

    Just curious if option (b) is more efficient than option (a)? At the first glance, option (a) will have several times of more operations than option (b). But I did some simulations for a million rows in df, option (b) is just a fraction faster on average. Does it mean the Pandas will group all the scalar operations in option (a) automatically?

    (a) Variable a, b, c, d, e, f are all scalars.

    df['val2'] = (a*b+c*d)*df['val1']*e/f


    (b)

    x = (a*b+c*d)*e/f
    df['val2'] = df['val1']*x

    Continue reading...

Compartilhe esta Página