Start learning free

LESSON 25 OF 165 · MACHINE LEARNING: ANALYSIS PROJECTS

Who Are the Best Customers?

Practice

Does the shop's money come from many customers or from a few? customers.csv has one row per customer, and its spent column is what each one paid in total. You rank the customers by it. Then you see what share of all revenue the top 10% bring, and what share the bottom half bring.

Sorting a table: df.sort_values("col", ascending=False) gives back the whole table sorted by one column, biggest first. Whole rows move and keep their labels, and df stays as it was. df[["a", "b"]], with a list inside the brackets, keeps only those columns. .head(n) gives back the first n rows and .tail(n) the last n. Here is an example on a small made-up table:

pets = pd.DataFrame({"name": ["Rex", "Tom", "Bo", "Kit"], "meals": [5, 9, 2, 4]})
fed = pets.sort_values("meals", ascending=False)    # Tom 9, Rex 5, Kit 4, Bo 2
print(fed[["name", "meals"]].head(2).to_string())   # Tom and Rex, labels 1 and 0
print(fed["meals"].tail(2).sum())                   # 4 + 2 = 6

On a sorted table, the first rows are the biggest spenders and the last rows are the smallest. len(df) is the number of rows, // divides and drops the decimals, and round(x, 1) rounds one number to 1 decimal. Your script must print:

     customer_id  visits  orders  spent
0              1      11       6    720
62            63      12       4    666
73            74      14       6    665
157          158       5       5    655
153          154      14       5    598
3              4       1       3    597
178          179      11       5    569
86            87      15       6    564
225          226      15       6    544
245          246      16       6    538
The top 30 customers brought 15613 of 56978: 27.4% of all revenue; the bottom half brought 19.5%.

Your task: customers.csv is already read into df. Sort the customers by spent and print the top 10. Work out what share of the total the top 10% spent, and what share the bottom half spent. Print the answer in a sentence.


Assignment
Follow the Coding Tutorial to rank the customers, print the top 10, and compare the top 10% with the bottom half.


Hint
Take the top and the bottom rows from ranked, not from df: only the sorted table has the biggest spenders first. Work out the size of the top 10% from len(df) instead of typing 30.


STEP 1 OF 9
    Ctrl + Enter to check