Prepare every column in one object. Build a ColumnTransformer with:
age, income, loan_amount: a pipeline of SimpleImputer(strategy="median") then StandardScaler()city, employment: a pipeline of SimpleImputer(strategy="most_frequent") then OneHotEncoder(handle_unknown="ignore")(country is left out.) Fit it on X_train and store the shape of the transformed X_test as a list [rows, columns] in result.
import pandas as pd
import numpy as np
loans = pd.DataFrame({
"app_id": list(range(1, 31)),
"age": [25, 32, 47, 51, 29, 38, 44, 23, 36, 58, 41, 27, 33, 49, 30,
26, 39, 55, 34, 45, 28, 31, 52, 37, 24, 42, 35, 48, 29, 40],
"income": [32000, 54000, 88000, 95000, 41000, 61000, np.nan, 28000, 58000, 110000, 72000, 35000, 50000, 83000, 47000,
30000, 64000, 2500000, 52000, 79000, 39000, np.nan, 99000, 60000, 26000, 70000, 55000, 87000, 42000, 68000],
"loan_amount": [150000, 250000, 400000, 450000, 200000, 300000, 350000, 120000, 280000, 500000, 320000, 160000, 240000,
380000, 210000, 140000, 290000, 420000, 250000, 360000, 180000, 230000, 470000, 270000, 110000, 330000,
260000, 410000, 190000, 310000],
"city": ["Pune", "Delhi", "Mumbai", "Pune", "Delhi", "Mumbai", "Pune", "Jaipur", "Delhi", "Mumbai", "Pune", None,
"Delhi", "Mumbai", "Pune", "Jaipur", "Delhi", "Mumbai", "Pune", "Delhi", "Jaipur", "Pune", "Mumbai", "Delhi",
"Jaipur", "Pune", "Delhi", "Mumbai", "Pune", "Delhi"],
"employment": ["Salaried", "Salaried", "Self-employed", "Salaried", "Self-employed", "Salaried", "Salaried",
"Self-employed", "Salaried", "Salaried", "Self-employed", "Salaried", "Salaried", "Salaried",
"Self-employed", "Self-employed", "Salaried", "Salaried", "Salaried", "Self-employed", "Salaried",
"Self-employed", "Salaried", "Salaried", "Self-employed", "Salaried", "Salaried", "Self-employed",
"Salaried", "Salaried"],
"country": ["India"] * 30,
"defaulted": [1, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0],
})
from sklearn.model_selection import train_test_split
X = loans.drop(columns=["app_id", "defaulted"])
y = loans["defaulted"]
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=42, stratify=y)Store your final answer in a variable named result.
Each hint gives a little more help. Try on your own first.
Run your code to see the output here.