A table is not fixed: you can make new columns out of the ones you have. Assign to a new name in square brackets, df["name"] = …, the way you add a new key to a dict. Math between two columns works row by row: dividing one column by another gives back a column with one answer per row, with no loop.
A comparison on a column gives back a True/False column, one answer per row, and you can store it like any other column. Its .sum() is the number of True rows, because True counts as 1 and False as 0. To turn a condition into two labels, use np.where(condition, a, b): it gives back a for every row where the condition is True and b for the others.
df["months"] = df["days_since_last"] / 30
df["subscribed"] = df["newsletter"] == "yes"
print("Subscribers:", df["subscribed"].sum())
df["status"] = np.where(df["days_since_last"] > 90, "asleep", "active")
To print a neat table, .round(2) gives back a copy with every number rounded to 2 decimals. Your program must print:
spent orders per_order
0 720 6 120.00
1 201 3 67.00
2 257 3 85.67
Regulars: 89
spent visits regular group
0 720 11 True big spender
1 201 7 False normal
2 257 5 False normal
3 597 1 False big spender
Your task: make a column per_order (each row's spent divided by its orders), a True/False column regular (visits is 10 or more) and a column group with np.where: "big spender" where spent is over 300, else "normal". Print them as shown above.
Assignment
Follow the Coding Tutorial to make the three new columns and print them.
Hint
Each new column is one line: the new name in square brackets on the left of =, the column math on the right. np is numpy, already imported at the top of the file.
Free plan: 30 tutor messages. PRO is unlimited.
