filippo
filippo

Reputation: 5294

Pandas, select maximum from one column and minimum from another

I have a dataframe like this

A         B
25        0.5
21        0.6
17        0.7
14        0.7   <--- this is the row I want
12        0.3

I'd like to select the maximum B with minimum A.

Is there a pandas easy trick to do this?

Upvotes: 1

Views: 406

Answers (2)

jezrael
jezrael

Reputation: 863731

First compare column B by max values and then get index of minimal A by idxmin, last select by loc:

a = df.loc[df['B'] == df['B'].max(), 'A'].idxmin()
print (a)
3

#for one row DataFrame use [[]]
df = df.loc[[a]]
print (df)
    A    B
3  14  0.7

#for Series use []
s = df.loc[a]
print (s)
A    14.0
B     0.7
Name: 3, dtype: float64

Detail:

print (df.loc[df['B'] == df['B'].max(), 'A'])

2    17
3    14
Name: A, dtype: int64

Upvotes: 1

cs95
cs95

Reputation: 403218

IIUC, using where + idxmin:

df.iloc[df.where(df.B.eq(df.B.max())).A.idxmin()]

A    14.0
B     0.7
Name: 3, dtype: float64

Upvotes: 1

Related Questions