Home > Back-end >  How to return max value from a row from pandas dataframe taking into account values from the last ro
How to return max value from a row from pandas dataframe taking into account values from the last ro

Time:04-01

Currently I'm returning column name of the max value in the each row.

df['Active'] = df.idxmax(axis=1)

enter image description here

How do I take into account the Priority for each column? e.g. for Row 0, the Active column should have opC since it has a higher priority than opA. (Also Priority row shouldn't return anything in the Active column).

CodePudding user response:

You need to resort the columns before using idxmax

temp_cols = df.columns
df = df.sort_index(axis=1,key=lambda x:df.loc['Priority',x],ascending=False)
df['Active'] = df.idxmax(axis=1)
df = df[list(temp_cols) ['Active']]
df.loc['Priority','Active'] = ''

CodePudding user response:

multiply column index by row column value , then pick up maximum result and sum all the row values , put it in new column , sort column.

  • Related