Start learning free

LESSON 24 OF 165 · MACHINE LEARNING: ANALYSIS PROJECTS

Revenue per Month in Python

Practice

Is the shop growing? To find out, you add up the paid revenue of each month and compare every month with the month before. The starting code reads orders.csv into orders and already adds its revenue column: quantity times unit_price.

From text to months: read_csv reads the date column as plain text. pd.to_datetime(column) gives back real dates, and .dt.month gives back each date's month as a number from 1 to 12. Group the paid lines by that number and add up their revenue, and you get one total per month, in month order.

Comparing neighbours: on a Series, .diff() gives back each value minus the value before it. .pct_change() gives back that change divided by the value before, so 0.25 means +25%. The first row has nothing before it, so both give NaN ("not a number") there. .idxmax() and .idxmin() give back the label of the biggest and the smallest value, and they skip NaN. Here is an example on a small made-up Series of visits per day:

visits = pd.Series([40, 50, 45], index=[1, 2, 3])
print(visits.diff())          # NaN, 10.0, -5.0
print(visits.pct_change())    # NaN, 0.25 (+25%), -0.1 (-10%)
print(visits.idxmax())        # 2: the label of 50, not 50 itself

Your script must print:

       revenue  change  growth
month                         
1          552     NaN     NaN
2          919   367.0    66.5
3         1580   661.0    71.9
4         2203   623.0    39.4
5         3020   817.0    37.1
6         4470  1450.0    48.0
7         3754  -716.0   -16.0
8         5562  1808.0    48.2
9        10137  4575.0    82.3
10       11890  1753.0    17.3
11       12891  1001.0     8.4
Best month: 11 (12891), worst: 1 (552); the biggest fall came in month 7 (-716.0).

Your task: add a month column, keep only the paid lines and add up their revenue per month. Work out the change from the month before, in money and in percent. Print all three as one table, then print a sentence with the best month, the worst month and the month of the biggest fall.


Assignment
Follow the Coding Tutorial to add up the revenue per month, compare each month with the one before, and name the best month, the worst month and the biggest fall.


Hint
The biggest fall is the most negative change, so it is the smallest value of change, not of monthly. Multiply pct_change() by 100 inside parentheses before .round(1).


STEP 1 OF 11
    Ctrl + Enter to check

    Da Monthly Revenue in Python

    Keep going with Python1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free