1

I have a DataFrame object:

fruit   quantity
apple   500
pear    400
orange  300

I wish to search for the smallest value in column quantity, then get the corresponding value in column fruit.

Currently my solution is:

df.sort_values(by='quantity',ascending=True)['fruit'][0] I expect this to return 'orange'.

Is there a better way to do this?

Gen Tan
  • 858
  • 1
  • 11
  • 26

2 Answers2

2

Try this to get the index of the minimum value of a pandas.Series column with .idxmin() method and use .loc to get the corresponding value in column fruit

df.loc[df.quantity.idxmin(), 'fruit']
AdibP
  • 2,819
  • 1
  • 10
  • 24
1

If want first quantity of first minimal value of quantity use DataFrame.set_index for index and then Series.idxmin:

out = df.set_index('fruit')['quantity'].idxmin()
print (out)
orange

If possible multiple minimal values use boolean indexing:

out = df.loc[df['quantity'].eq(df['quantity'].min()), 'fruit'].tolist()
print (out)
['orange']
jezrael
  • 822,522
  • 95
  • 1,334
  • 1,252