Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the column for a column having max value in python?

I have a dataframe:

df = pd.DataFrame({'p1_c': [1,10,3,40],
                   'p2_c': [4,3,4,14],
                   'p3_c': [5,2,8,78],
                   'p1_v': [776,1776,300,600],
                   'p2_v': [998,98,100,100],
                   'p3_v': [800,80,50,500]
                  })
df
   p1_c  p2_c  p3_c  p1_v  p2_v  p3_v
0     1     4     5   776   998   800
1    10     3     2  1776    98    80
2     3     4     8   300   100    50
3    40    14    78   600   100   500

(p1_c,p1_v),(p2_c,p2_v),(p3_c,p3_v) are in groups and describing same thing.
I want the get the v-th column value of the one having the highest c-th value

For example see in row 0 :

df[[p1_c,p2_c,p3_c]].max(axis=1)   
#get the max value i.e p3_c

So I want p3_v value as an output (i.e 800). Same pattern followed by row 1,2,and 3.

EXPECTED OUTPUT

   p1_c  p2_c  p3_c  p1_v   p2_v  p3_v  RESULT
 0  1     4     5    776    998    800   800
 1  10    3     2    1776    98    80    1776
 2  3     4     8    300    100    50    50
 3  40   154    78   600    100    500   100
like image 831
Amit Avatar asked Feb 10 '26 20:02

Amit


1 Answers

You could try this with df.to_records, that I find simpler, and could be the fastest way:

df['RESULT']=[row[list(row).index(max(list(row)[1:4]))+3]for row in df.to_records()]
print(df)

Output:

   p1_c  p2_c  p3_c  p1_v  p2_v  p3_v  RESULT
0     1     4     5   776   998   800     800
1    10     3     2  1776    98    80    1776
2     3     4     8   300   100    50      50
3    40    14    78   600   100   500     500
like image 79
MrNobody33 Avatar answered Feb 12 '26 14:02

MrNobody33