Data Analyst Program

Python · Week 3 of 4 · 5 hours

Functions and NumPy Basics

Package your code into reusable functions and calculate quickly on arrays.

Learning objectives

By the end of this week you will be able to:

  • Define functions with parameters and return values.
  • Explain why functions make analysis easier to repeat.
  • Create NumPy arrays and do vectorized math.
  • Use NumPy statistics functions and boolean filtering.

Lessons

Functions

A function is a named, reusable block of code. You have already used built-in ones (print, len, sum). Now you will write your own.

def calculate_revenue(units, price, discount=0):
    '''Return revenue after an optional discount (0.1 = 10%).'''
    revenue = units * price * (1 - discount)
    return round(revenue, 2)

calculate_revenue(10, 4.5)        # 45.0
calculate_revenue(10, 4.5, 0.1)   # 40.5
  • def starts the definition; the indented lines are the body.
  • Parameters (units, price, discount) are the inputs. discount=0 is a default used if you leave it out.
  • return sends a result back. A function without return gives back None.
  • The text in triple quotes is a docstring explaining what the function does.

Why bother? If you clean data the same way every month, a function lets you do it with one line, and if you find a mistake you fix it in one place. A good rule: if you copy and paste code a third time, make it a function.

NumPy Basics

NumPy (Numerical Python) adds the array: a grid of numbers that Python can calculate on very quickly. Import it with the standard nickname:

import numpy as np
prices = np.array([19.99, 5.49, 12.00, 7.25])

Vectorized math means one operation applies to every element without a loop:

prices * 1.1            # add 10% to every price
prices + 1              # add 1 to every price
prices.mean(), prices.max(), prices.sum()
np.median(prices), prices.std()

Boolean filtering picks out elements that meet a condition:

prices > 10              # array([ True, False,  True, False])
prices[prices > 10]      # array([19.99, 12.  ])

Arrays can have two dimensions (rows and columns). arr.shape tells you their size, such as (4, 3) for 4 rows and 3 columns.

Why it matters: pandas, the library you learn next week, is built on top of NumPy. The same ideas (vectorized math and boolean filters) are how you will work with whole columns of data.

Watch

Practice

  1. Write a function shipping_cost(total) that uses your Week 2 shipping rules and returns the cost. Test it on three totals.
  2. Write clean_region(text) that strips spaces and capitalizes the first letter, and test it on " nORTH ".
  3. Create a NumPy array of 12 monthly sales figures. Calculate the mean, median, standard deviation, the best month and the months above average.
  4. Calculate month-over-month percent change: np.diff(sales) / sales[:-1] * 100.

Check your understanding

Try each question first, then open it to see the answer.

What does a function return if it has no return statement?

None.

What is the result of np.array([1,2,3]) * 2?

array([2, 4, 6]).

How do you select values above 100 from an array called a?

a[a > 100].

Assignment

Submit your notebook with both functions (including docstrings and tests) and the monthly sales analysis.