1

I have following sample data-set.

 raw_data = {'name': ['Willard Morris', 'Al Jennings', 'Omar Mullins', 'Spencer 
 McDaniel'],
            'age': [20, 19, 22, 21],
            'favorite_color': ['blue', 'blue', 'yellow', "green"],
            'grade': [88, 92, 95, 70]}

 df = pd.DataFrame(raw_data)
 df.head()

I am interested in finding max, min grade for a specific color say 'blue' how can i find it out.

The solution i have is following.. is there a better way. I have a huge data-set performance is also a criteria while selecting options available.

for i in df.index:
    if df.at[i, 'server_ip'] == 'blue':
        if min_grade > df.at[i,'grade']:
           min_grade = df.at[i,'grade']
        if max_grade < df.at[i,'grade']:
           max_grade = df.at[i,'grade']
4
  • 2
    question has nothing to do with machine-learning - kindly do not spam the tag (removed) Commented Jul 5, 2018 at 14:42
  • df[df.favorite_color == "blue"]["grade"].min() df[df.favorite_color == "blue"]["grade"].max() Commented Jul 5, 2018 at 14:45
  • Possible duplicate of Groupby max value and return corresponding row in pandas dataframe Commented Jul 5, 2018 at 14:52
  • Thanks this helped. Commented Jul 5, 2018 at 15:11

1 Answer 1

1

I would personally use .loc here

df.loc[df['favorite_color']=='blue','grade'].max()
df.loc[df['favorite_color']=='blue','grade'].min()

Edit 1

If you don't want to search twice, just save the result of .loc first then conduct the aggregation

data = df.loc[df['favorite_color']=='blue','grade']
min = data.min()
max = data.max()

Edit 2

If you want to search max and min for every color, use groupby

grouped = df.groupby('favorite_color')['grade']
max = grouped.max()
min = grouped.min()
Sign up to request clarification or add additional context in comments.

4 Comments

When we are finding max why can't we find min also?. Can't we stop multiple iterations?.
See edits ... also feel free to hit that green check to the left!
I was looking for a solution to find max and min for all unique values of favorite_color. Any solutions?
In that case, you should use groupby

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.