Introduction to NumPy Arrays

Python lists are a good introduction to NumPy arrays. There are a lot of similarities in how they are used, but also a few differences.

To use NumPy you need to install it on your system. While it comes included with Python distributions like Anaconda, a typical python installation will not include NumPy so you need to run: “pip3 install numpy” to include it in your development environment.

After it is installed, you also need to import NumPy into your script with: “import numpy as np”. The np alias is not required, but it will save you some typing and is good to know when you are trying to read other people’s code as it is fairly common.

How are NumPy arrays different than regular Python Lists?

  • They only allow one data type
  • as a result of having only one data type, they process much faster
  • you can do linear algebra type math with the arrays as in the example below:
my_list = [1,2,3,4,5,6,7,8,9,0]
new_list = my_list + [2]
import numpy as np
np_list = np.array(my_list) + 2

Check out this example… when you add to a NumPy array, the number gets added to every element in the array (as opposed to adding a new element to your list.) This is very powerful, especially when we start analyzing data. Not just addition, but all kinds of math works the same way!

You can also use numpy arrays in more complex mathematical equations. For example a list of radius measurements:

radius = [1,2,3,4,5]

pi = 3.14

areas = pi*radius**2 will then give you an array of the area of all the circles with the radius on your original lists.

Subsetting with NumPy Arrays

To access an element of a NumPy array the syntax is very similar to accessing elements in a list: my_array[2] for example.

But you an also do other cool stuff with a numpy array. For example, take the whole array: areas > 15 will return a new array with boolean values for each of the values in the areas array.

Or: areas[areas>15] which will return a new array of only those values which meet your criteria. This is some very convenient filtering abilities with just a tiny bit of code.

I hope you enjoyed this introduction to numpy arrays. (I only put this concluding sentence in for SEO purposes…)