Select higher value per row of two columns (Python)

Asked

Viewed 926 times

0

I have a dataframe with several columns, the last two are where I sum and multiply the other columns, at the end I create a column that should select the highest value between these two columns, for example:

inserir a descrição da imagem aqui

I ended up doing a 'FOR' to go through each line, but as it is a large dataframe, it ends up taking a long time.

Is there any other way to do it?

  • Try this: df['soma_final'] = df.loc[:, ['soma1', 'soma2']].max(1)

1 answer

0


You can use the .apply().

def max_value(row):
    return max(row['soma'], row['multiplicacao'])

df['max'] = df.apply(max_value, axis=1)

The apply function applies a function to each row (when Axis = 1) or to each column (when Axis = 0). I didn’t test the solution so I don’t know if there will be a difference in performance.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.