import pandas as pd summary = ( df.groupby('category') .agg( n=('price', 'size'), avg_price=('price', 'mean'), top_price=('price', 'max'), ) .reset_index() ) # Rank WITHIN each category, best first df['rank'] = ( df.groupby('category')['price'] .rank(method='dense', ascending=False) .astype(int) ) # Safe conditional assignment — one .loc, never chained indexing df.loc[df['price'] > 100, 'tier'] = 'premium'