Numpy is the core library for scientific computing in Python. Amongst other things, it provides with the ability to create multidimensional array objects and the tools to manipulate them further. This is important, because Python does not natively support Arrays, rather is has Lists, which are the closest equivalent to Arrays.
If you don’t have python Numpy installed already, refer to our getting started guide to see how to install python libraries.
Numpy stands for ‘Numerical Python’
Arrays in numpy
Bringing support for multi-dimensional arrays and supporting tools is what Numpy is most well known for. We’ll be going through the different ways to create and manipulate arrays.
What are Arrays?
In programming, an Array is a data structure which can store a fixed number of elements of the same data type within it. But where do we use Arrays? Let’s say we wanted to store 1000 values. It would incredibly slow and inefficient to create a 1000 variables to store the data.
Hence, we use Arrays, we can store an almost infinite number of values within it. You may think of an Array, as a collection of variables.
There are at least 5-6 different ways to create arrays in Python numpy. The ones mentioned below are some of the most common, and you likely won’t ever need to use anything else.
The first way is to explicitly define an array by defining it’s dimensions ad values.
# Commonly abbreviated to np import numpy as np arr = np.array([1,2,3]) print("One dimensional array \n", arr) arr = np.array([[1,2,3], [4,5,6]]) print("Two dimensional array \n",arr)
# OUTPUT One dimensional array [1 2 3] Two dimensional array [[1 2 3] [4 5 6]]
Creates an array of a specified size with all the values set to zero.
# SYNTAX numpy.zeros(shape, dtype = float)
The dtype parameter is optional, with it’s default value being float. So if you don’t want you values in decimal points, switch to int.
import numpy as np arr = np.zeros(5) print("Array 1 \n" ,arr) arr = np.zeros((5,2)) print("Array 2 \n", arr) arr = np.zeros((5,2), dtype = int) print("Array 3 \n",arr)
# OUTPUT Array 1 [0. 0. 0. 0. 0.] Array 2 [[0. 0.] [0. 0.] [0. 0.] [0. 0.] [0. 0.]] Array 3 [[0 0] [0 0] [0 0] [0 0] [0 0]]
There is another function which you can use by calling numpy.ones. It’s the exact same as np.zeros, except instead of zeros, the values are set to one.
Iterating Over Numpy Arrays
There are two approaches to iterating over an array. You can either use for loops or use in built numpy functions. We’ll cover both here. (We’ll only be doing two dimensional arrays, as that’s the real issue. Concept remains the same however).
For loop approach
First we find the lengths of the number of rows and columns in the array. Using the
len() function on the array will only return number of rows. However, finding the
len() of a row will return the number of elements in it, also known as the number of columns.
We set up two
for loops, as it’s a two dimensional array. The changing
i variables allow us to go through each index, printing them out individually.
import numpy as np arr2 = np.array([[1,2,3], [4,5,6]]) row_len = len(arr2) col_len = len(arr2) for x in range(row_len): for i in range(col_len): print(arr2[x][i])
This method should only be used on a basic level, as the it’s not suitable for handling complex arrays (Like three dimensional or more sized arrays)
This numpy function generates an iterator object once an array is passed into it’s parameters. The iterator object can then be used as shown below.
import numpy as np arr2 = np.array([[1,2,3], [4,5,6]]) for x in np.nditer(arr2): print(x)
As you can see, this method is much faster and requires less coding. The for loop approach is still important though. Numpy is a python library. You may end up using the For loop approach in other languages.
Arithmetic Operations for Arrays
You can perform basic Arithmetic operations on numpy arrays just like you would on any other variable. Some examples shown below.
import numpy as np arr1 = np.array([1,2,3]) arr2 = np.array([[1,2,3], [4,5,6]]) arr1 = arr1 + 1 print("Array 1, plus one \n", arr1) arr2 = arr2 * 2 print("Array 2, multiplied by two \n", arr2) sum = arr1 + arr2 print("Sum of both arrays \n", sum)
Array 1, plus one [2 3 4] Array 2, multiplied by two [[ 2 4 6] [ 8 10 12]] Sum of both arrays [[ 4 7 10] [10 13 16]]
Numpy Math Functions
Numpy has a whole host of built-in-functions for math and related material. We’ll be demonstrating the use of several of these functions that can be used for arrays.
#Sum of two arrays sum = np.add(arr1,arr2) print("Sum of two arrays \n", sum) #Sum of all the elements in an array sum = np.sum(arr1) print("Sum of all elements \n", sum) #Square of an array squareroot = np.sqrt(arr1) print("Square of arr1 \n", squareroot) #Square of an array square = np.square(arr1) print("Square of arr1 \n", square) #Transpose of an array trans = arr1.T print("Transpose \n", trans) #Log of each element log = np.log(arr1) print("Log of an array \n", log)
The above functions are pretty self explanatory and the comments explain their use. Try using them on your own to understand them better.
Numpy is a vast library and we can’t possibly hope to cover it in a single page. This page was dedicated to covering all the major functions and uses of Arrays in numpy. Feel free to search the numpy docs for more information, or await future articles from as at Coderslegacy.