0

Let's say that I want to find the person that ate the most tacos from a taco eating competition.

DataFrame

df = pd.DataFrame({'tacos':[5,10,7]},index=['John','Carlos','Peter'])

If I have identified the max tacos a person has eaten, then how I could get the name of that person as a string?

maxtacos = df['Tacos'].max()


df.get(df[Name], df['Tacos', maxtacos])

I would like to get "Carlos" as a result.

Thank you

3
  • 1
    df.loc[df['Tacos'].eq(df['Tacos'].max(), 'Name'].tolist() You can have more than one person...
    – Alexander
    Commented Oct 29, 2019 at 23:58
  • This is returning the complete row with all the columns, instead, I would like to get "Carlos" as a string.
    – iDevPy
    Commented Oct 30, 2019 at 1:56
  • 1
    As I mentioned, you can have more than one person who ate the max number of tacos, e.g. df = pd.DataFrame({'Tacos': [5, 5, 1], 'Name': ['John', 'Harry', 'Bill']}). Note that idxmax only gives you the first name that matches the max value, the method above gives you the list of all names, i.e. df.loc[df['Tacos'].eq(df['Tacos'].max()), 'Name'].tolist() results in ['John', 'Harry'].
    – Alexander
    Commented Oct 30, 2019 at 3:47

1 Answer 1

1

If I understand correctly, then you should be able to use df.idxmax():

df = pd.DataFrame({'tacos':[5,10,7]},index=['John','Carlos','Peter'])
df.idxmax()

That will return Carlos in this example.

Now, if you want the value of another column, you could do something like this:

df = pd.DataFrame({'tacos':[5,10,7],'beers':[1,2,3]},index=['John','Carlos','Peter'])
df['beers'].loc[df['tacos'].idxmax()]

That would tell you that the person who ate the most tacos drank 2 beers.

2

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.