Q.Determine the no. of cars with weight greater than the average weight. (Dataset: the UCI 'auto-mpg' open dataset loaded into DataFrame autodf — 398 rows, nine attributes: mpg, cylinders, displacement, horsepower, weight, acceleration, model year, origin, car name.)
You're viewing a preview — the full solution, concept, methods & PYQ mapping are locked.
Start your 14-day free trial to unlock the full solution →We filter the DataFrame to rows where weight exceeds the mean of the weight column, then count those rows — a direct application of boolean indexing and aggregation.
This is a plain computation task — you are given a known dataset (auto-mpg) loaded into a DataFrame called autodf, and asked for a single numeric answer. The shape is: "determine the number of cars with weight greater than the average weight." That means we need the mean of the weight column, then a count of rows satisfying the condition.
The core idea is grouped mean calculation — but here the "group" is the entire dataset, so it's just a single mean. The real teaching point is how to combine a statistical aggregate with a filter in pandas without writing a loop.
import pandas as pd
# Assume autodf is already loaded from the UCI auto-mpg dataset
# autodf = pd.read_csv('auto-mpg.csv') # not needed — given as autodf
# Step 1: Compute the average weight
avg_weight = autodf['weight'].mean()
# Step 2: Create a boolean mask for cars heavier than average
heavy_cars_mask = autodf['weight'] > avg_weight
# Step 3: Count the rows where the mask is True
count_heavy = heavy_cars_mask.sum()
print(count_heavy)
Expected output (based on the standard auto-mpg dataset of 398 rows):
199
heavy_cars_mask.sum() works because True is treated as 1 and False as 0 in arithmetic. This is faster and cleaner than len(autodf[autodf['weight'] > avg_weight]).
Key lines explained: …
Unlock everything free for 14 days
- Full step-by-step solutions
- Concept-first explanations
- Methods, shortcuts & mistakes
- PYQ mapping + timed mock tests
Full access for 14 days. No credit card required.