Target encoding replaces a category with the average outcome for it. Cities with few rows get extreme averages, so blend each city's churn rate with the overall rate:
encoded = (n × city_rate + m × overall_rate) / (n + m), with m = 2, where n is the city's number of subscribers.
Store a dictionary {city: encoded} with values rounded to 3 decimals in result.
import pandas as pd
subs = pd.DataFrame({
"sub_id": list(range(1, 13)),
"city": ["Pune", "Pune", "Pune", "Delhi", "Delhi", "Delhi", "Delhi", "Mumbai", "Mumbai", "Jaipur", "Pune", "Delhi"],
"plan": ["Basic", "Premium", "Basic", "Basic", "Premium", "Basic", "Basic", "Premium", "Basic", "Basic", "Premium", "Premium"],
"watch_hours": [12, 40, 5, 8, 35, 3, 10, 50, 6, 2, 45, 30],
"support_calls": [1, 0, 3, 2, 0, 4, 1, 0, 2, 5, 0, 1],
"refund_amount": [0, 0, 199, 199, 0, 199, 0, 0, 199, 199, 0, 0],
"churned": [0, 0, 1, 1, 0, 1, 0, 0, 1, 1, 0, 0],
})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.