1

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?

filippo
  • 5,197
  • 2
  • 21
  • 44
  • Possible duplicate of [Pandas DataFrame - Find row where values for column is maximal](https://stackoverflow.com/questions/10202570/pandas-dataframe-find-row-where-values-for-column-is-maximal) – jpp Mar 07 '18 at 09:54
  • 2
    Typically I'd agree but I don't think that duplicate covers it – cs95 Mar 07 '18 at 10:22
  • @jpp don't know, there's probably a duplicate somewhere in this site, given it's a really easy question, but it's not that one – filippo Mar 08 '18 at 08:15
  • 1
    @filippo - Dont worry, if question will be closed, let me or cᴏʟᴅsᴘᴇᴇᴅ know and question will be reopened. ;) – jezrael Mar 08 '18 at 08:16

2 Answers2

1

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
cs95
  • 379,657
  • 97
  • 704
  • 746
1

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
jezrael
  • 822,522
  • 95
  • 1,334
  • 1,252