The column bought_again is 1 for a customer who bought again and 0 for one who didn't. The mean of a 0/1 column is the share of 1s, so df["bought_again"].mean() gives back the share of customers who came back. This lesson asks: which group of customers comes back much more, or much less, than average?
df.groupby("col")["bought_again"].mean() splits the rows into groups by the values of col and gives back one mean per group, as a Series labeled by the groups. A small example on made-up page visits:
visits = pd.DataFrame({"device": ["phone", "phone", "laptop", "laptop", "phone"],
"clicked": [1, 0, 1, 1, 0]})
print(visits["clicked"].mean()) # 0.6
print(visits.groupby("device")["clicked"].mean()) # laptop 1.0, phone 0.333…
pd.concat([a, b], keys=["x", "y"]) stacks several Series into one long Series and puts each key in front of its part's labels, so every label becomes a pair like ("x", "phone"). Subtracting a number from a Series subtracts it from every value. .abs() gives back each value without its sign, and .idxmax() gives back the label of the largest value, not the value. pd.DataFrame({"a": s1, "b": s2}) puts two Series side by side as columns.
The starting code reads customers.csv and cleans city: spaces cut, names written like Cluj, blanks filled with Unknown. Your script must print:
Overall: 0.597
rate gap
newsletter no 0.485 -0.112
yes 0.737 0.140
city Berlin 0.523 -0.074
Cluj 0.519 -0.077
Lyon 0.688 0.091
Madrid 0.627 0.031
Porto 0.609 0.012
Rome 0.620 0.023
Unknown 0.556 -0.041
returned_item 0 0.611 0.015
1 0.486 -0.111
newsletter = yes differs most: 0.737 bought again, against 0.597 overall.
Your task: print the overall rate, then one table with the rate and the gap from the overall rate for every newsletter, city and returned_item group, and finish with a sentence naming the group that differs most. Round every rate and gap to 3 decimals.
Assignment
Follow the Coding Tutorial to compare the bought-again rate of each group with the overall rate and find the group that differs most.
Hint
The three groupby lines have the same shape: only the column you group by changes. Because of keys, idxmax gives back a pair, so unpack it into two names; rates[column][group] then picks that group's rate.
Free plan: 30 tutor messages. PRO is unlimited.
