A Simple Guide to NumPy in Python | by Frank Andrade | Towards Data Science

NumPy is a Python library on which most data science packages such as SciPy (Scientific Python), Matplotlib, and Scikit-learn depends to some extent. It adds support for large, multi-dimensional arrays and matrices, along with a large collection of high-level mathematical functions to operate on these arrays.
Without a doubt, Numpy is a library that you should learn if you are a data science enthusiast. This is why, in this guide, I’ll show you all the things you can do with the Numpy library.
Below, you’ll find the topics covered in this guide:
Table of Contents1. How to Create an Array - Create arrays from lists - Create arrays with 0’s, 1’s, and a random number - Create arrays with a range of elements2. Basic Operations3. Array Manipulation - Transposing and Reshaping a matrix - Indexing and Slicing - Concatenate arrays
To start with this guide, let’s install the Numpy library.
pip install numpy
After this, we have to import the library to start working with Numpy.
import numpy as np
In Numpy, most of the time we work with arrays. An array is a grid of values that contains information about the raw data, how to locate an element, and how to interpret an element. Some examples of arrays are vectors (an array with a single column) and matrices (an array with multiple columns).
There are different ways to create arrays in Numpy. Let’s write some code to create arrays.
We can create an array from Python lists, we just have to insert the list inside np.array() as shown below.
a = np.array([1,2,3])IN [0]: print(a)IN [1]: print(f'Dimension: {a.ndim}')OUT [0]: [1 2 3]OUT [1]: Dimension: 1
We just created a 1D array (we can get the dimension using.ndim). Now let’s create a 2D array.
b = np.array([[1.5,2,3], [4,5,6]],dtype=float)IN [0]: print(b)IN [1]: print(f'Dimension: {b.ndim}')OUT [0]: [[1.5 2.  3. ]          [4.  5.  6. ]]OUT [1]: Dimension: 2
A 2D array stores multiple data elements of the same type in a matrix or table-like format with a number of rows and columns.
We can easily create an array filled with 0’s or 1’s and even specify the dimension.
Let’s create an array of 2 rows and 3 columns filled with 0's.
IN [0]: np.zeros([2,3])OUT [0]: array([[0., 0., 0.],                [0., 0., 0.]])
In case you want to create a 1D array, write only the number of columns you wish to get.
IN [0]: np.ones(4)OUT [0]: array([1., 1., 1., 1.])
Also, you can create an array with a random number using np.full()
IN [0]: np.full([3,3], 8)OUT [0]: array([[8, 8, 8],                [8, 8, 8],                [8, 8, 8]])
Just like the built-in range() function, you can create an array with a range of elements. To do so, use np.arange()
IN [0]: np.arange(5,30,5)OUT [0]: array([ 5, 10, 15, 20, 25])
The three arguments included in the code above are:
start: integer starting from which the sequence of integers is to be returned
stop: integer before which the sequence of integers is to be returned (range ends at stop - 1)
step: integer value which determines the increment between each integer in the sequence
Basic operations such as addition, subtraction, multiplication, division, and many more can be easily executed with Numpy.
We’ll use the following Numpy arrays for the operations below.
a = np.array([2,3,4])b = np.array([[3,4,5], [6,7,8]])
To add to two or more arrays use np.add(a,b) or the + sign.
IN [0]: a+bOUT [1]: np.add(b,a)OUT [0]: [[ 5  7  9]          [ 8 10 12]]
To subtract one array from another use the np.subtract(a,b) or the — sign
IN [0]: a-bOUT [1]: np.subtract(a,b)OUT [0]: [[-1 -1 -1]          [-4 -4 -4]]
To multiply two arrays usenp.multiply(a,b)or the * sign.
IN [0]: a*bOUT [1]: np.multiply(a,b)OUT [0]: [[ 6 12 20]          [12 21 32]]
To divide two arrays usenp.divide(a,b)or the / sign.
IN [0]: b/aOUT [1]: np.divide(b,a)OUT [0]: [[1.5  1.33  1.25]          [3.   2.33  2.  ]]
Some useful aggregate functions are listed below.
a.sum()a.min()b.max(axis= 0)b.cumsum(axis= 1) #Cumulative sum a.mean()np.std(b) #Standard deviation
Just like Pandas dataframes, you can transpose, index, slice, and do more with Numpy arrays.
You can reshape a matrix using .reshape() and indicating the number of rows and columns you wish to have.
We’ll use the following Numpy array to test transposing and reshaping.
IN[0]: c = np.array([4,5,6,7,8,9])IN[1]: print(c)OUT[0]: [4 5 6 7 8 9]
Let’s set it to 2 rows and 3 columns.
IN[0]: c.reshape(2,3)OUT[0]: [[4 5 6]         [7 8 9]]
Now let’s set it to 3 columns and 2 rows and transpose the array. To transpose the array you can use either.transpose() or .T
IN[0]: c.reshape(3,2)IN[1]: c.TOUT[0]: [[4 5]         [6 7]         [8 9]]IN [1]: [[4 6 8]         [5 7 9]]
Indexing and slicing NumPy arrays work the same way as Python lists. Let’s have a look.
To get a specific element of an array we can use square brackets [] and specify the row and column
IN[0]: b = np.array([[3,4,5], [6,7,8]])IN[1]: b[1,2]OUT[0]: array([[3, 4, 5],              [6, 7, 8]])IN [1]: 8
Slicing enables accessing parts of an array sequence. You can specify where to start the slicing, and where to end.
IN[0]: a = np.arange(5,20,2)IN[1]: a[0:2]OUT[0]: [5 7 9 11 13 15 17 19]IN [1]: [5 7]
We can also set conditionals inside square brackets to filter elements out.
IN[0]: a = np.arange(5,20,2)IN[1]: a[a<10]OUT[0]: [5 7 9 11 13 15 17 19]IN [1]: array([5, 7, 9])
You can concatenate two arrays withnp.concatenate(). By default, it has axis=0 (rows)
a = np.array([[1, 2], [3, 4]])b = np.array([[5, 6], [7, 8]])IN[0]: np.concatenate((a, b))OUT[0]: array([[1, 2],               [3, 4],               [5, 6],               [7, 8]])
In case you want to concatenate by columns set axis=1.
IN[0]: np.concatenate((a, b), axis=1)OUT[0]: array([[1, 2, 5, 6],               [3, 4, 7, 8]])
That’s it! All the code written in this guide can be found on my Github. You can unlock more Numpy functionalities using it along with Pandas. Below there’s a guide to move from Excel to Python using the Pandas and Numpy library.
towardsdatascience.com
Join my email list with 3k+ people to get my Python for Data Science Cheat Sheet I use in all my tutorials (Free PDF)