PROJECT 070 · PYTHON SOURCE
Vehicle weight and fuel economy
Study-specific code. Shared modules, dependency versions, and reproduction instructions are included in all project files.
Download Python file ↓from pathlib import Path
import sys
ROOT = Path(__file__).resolve().parents[2]
sys.path.insert(0, str(ROOT))
import numpy as np
import pandas as pd
from scipy.stats import spearmanr
from sklearn.decomposition import PCA
from sklearn.ensemble import IsolationForest
from sklearn.preprocessing import StandardScaler
from sklearn.metrics import confusion_matrix, precision_score, recall_score
from portfolio.data import load
from portfolio.constants import *
from portfolio.methods import result, sql, rates, associations, distribution, regression, classification, cluster
from portfolio.engine import execute
META = {'id': 70, 'dataset': 'auto', 'title': 'Vehicle weight and fuel economy', 'question': 'How does fuel economy differ across declared vehicle-weight bands?', 'method': 'Robust fuel-economy summaries by weight band.', 'action': 'Use controlled vehicle comparisons before attributing fuel economy differences to weight alone.', 'limitations': "Historical city-cycle vehicle observations are not current fleet performance. Vehicle mix and model year are confounded. A '?' horsepower value means missing, not zero. "}
def analyze():
df = load('auto').copy()
df['weight_band']=pd.cut(df.weight,[0,2000,2500,3000,3500,4000,np.inf]).astype(str)
t=df.groupby('weight_band').mpg.agg(vehicles='size',median_mpg='median',p25=lambda s:s.quantile(.25),p75=lambda s:s.quantile(.75)).reset_index()
out=result(t,'weight_band','median_mpg','Miles per US gallon','Engine size, model year and origin differ across weight bands.')
return out
if __name__ == "__main__":
execute(Path(__file__).parent, META, analyze)