Numpy Guide for People In a Hurry

I will go over how to initialize Numpy arrays in multiple ways, access values within arrays, perform mathematical and matrix operations, and use arrays for masking as well as comparisons..I find Numpy arrays to be super helpful to use in solving Python coding puzzles.Let’s get started on the fun.NumpyFirst and foremost, you must import Numpy with the following code.import numpy as npMultiple Ways to Create Numpy ArraysUnlike a list, you are not able to create an empty Numpy array..Below are multiple ways to initialize a Numpy array depending on your needs.If you have a list that you would like to convert to a Numpy array, we can easily convert it.Accessing Elements In ArrayWe can access an individual item or a slice of data..Similar to lists, the first element is index at 0..For example, array1[0,0] indicates that we are accessing the first row and the first column..The first number in the tuple [0,0] indicates the index of the row and the second number indicates the index of the column.Broadcasting“The term broadcasting describes how numpy treats arrays with different shapes during arithmetic operations.” — SciPy.orgBroadcasting is a way in which one can get the outer product of two arrays.According to the documentation, “When operating on two arrays, NumPy compares their shapes element-wise..Two dimensions are compatible whenthey are equal, orone of them is 1If these conditions are not met, a ValueError: frames are not aligned exception is thrown, indicating that the arrays have incompatible shapes.”In order to successfully get the outer product, we use reshape..This method changes the shape of the array so that we can make it compatible for Numpy operations.Mathematical and Matrix CalculationsOne of the reasons I love Numpy arrays is that it’s super easy to manipulate..Concatenate, add, multiply, transpose with just one line of code!Below are some examples of various arithmetic and multiplicative operations with the Numpy arrays..Operations not covered below can be found in the documentation here.Other cool features include concatenating, splitting, transposing (switching items from rows to columns and vice versa), and getting the diagonal elements.Above, axis = 0 tells the computer that we want to concatenate by rows..If instead we want to concatenate by columns, we use axis = 1.Comparisons and MasksA useful thing we can do with Numpy arrays is to compare one array to another..A boolean matrix is returned in the comparison.We can use this boolean matrix to our advantage.. More details

Leave a Reply