Reputation: 821
I have the following dataframe:
a b c d e
1 .90 .95 .83 .56
.95 .96 .87 .83 .63
.83 .87 .83 .95 .81
How do I find the max value per row and the column it came from, so that it looks like:
a 1
b .96
d .95
Upvotes: 3
Views: 3277
Reputation: 812
maxRow = df.idxmax(1)
maxValue = df.max(1)
print(pd.concat([maxRow , maxValue],1))
The maxRow
variable gives the id of the maximum valued row in the dataframe,the 1 to to set the axis to row instead of column, Similarly, the maxValue
gets the maxValues of the rows
pd.concat
is to zip these two lists into a dataframe
Upvotes: 1
Reputation: 75080
using np.argmax
and df.lookup
:
s=pd.Series(df.columns[np.argmax(df.values,axis=1)])
final=pd.DataFrame(df.lookup(s.index,s),s)
Upvotes: 5
Reputation: 18367
You can use idxmax()
function:
import pandas as pd
a = {'a':[100,95,83],'b':[90,96,87],'c':[95,87,83],'d':[83,83,95],'e':[56,63,81]}
df = pd.DataFrame(a)
print(df)
Dataframe looks like this:
a b c d e
0 100 90 95 83 56
1 95 96 87 83 63
2 83 87 83 95 81
Using the function idxmax we get which column does the max value per row belong:
print(df.idxmax(axis=1))
Output:
0 a
1 b
2 d
Concatenating it with the original dataframe, to the get the corresponing value, given the column it belongs to.
df_result = pd.concat([df.idxmax(axis=1),df.max(axis=1)],axis=1)
print(df_result)
Output:
0 1
0 a 100
1 b 96
2 d 95
Upvotes: 2
Reputation: 93151
Try this:
result = df.max(axis=1)
result.index = df.idxmax(axis=1)
Upvotes: 5