1. Starting data handling in Python - NumPy#

1.1. import#

It’s time to crunch some data. Before that, we need to access some new modules. Last week, we used exclusively functions and data types in what’s known as ‘base’ Python - the bare bones installation.

But there are thousands of extra functions and data types out there to help with specific tasks, just like data handling. In order to actually use them, we need to use import, a special command that activates the modules and allows you to access them. NumPy and Pandas are examples of modules that need to be imported.

1.2. How import works#

When you import a module, you have access to all of its functions, data types, and submodules (collections of related functions). However, they all live under the import alias - a name that Python recognises the module as. You place all of your import statements at the top of your code or notebook. Once imported, the functions will be available until the end of the session. Importing NumPy works like this:

# Import NumPy!
import numpy
# Using the 'sqrt' function in NumPy
square_root = numpy.sqrt(40)
print(square_root)
6.324555320336759

1.3. import alias - importing something as#

You can see one issue with this. Everytime you import a module like NumPy, to use its functions, you have to type numpy.function_name, which can be a hassle. Thankfully, Python has the ability to assign modules to a name of your choosing, using the as keyword. This can be anything, but conventions indicate NumPy should be imported as np - its alias.

# Import NumPy with its conventional alias, and use it to calculate a square root
import numpy as np
print(np.sqrt(40))
6.324555320336759

1.4. Selective imports#

Some modules are massive, and you don’t need all the functions they offer. Python is flexible enough to let you take one or several functions to use from a module, without requiring the alias, using the from keyword.

# Import sqrt and square functions from NumPy
from numpy import sqrt, square

value = 10
print(sqrt(square(value)))
10.0

You can even selectively import a function and give it a different name! Be careful with this - down this road lies madness…

# Demonstrate selective import and aliasing
from numpy import square as SQUAREEEE
print(SQUAREEEE(value))
100