Getting started with NumPy

Getting started with NumPyBurningdzireBlockedUnblockFollowFollowingJan 4NumPy stands for Numerical Python and it is a core scientific computing library in Python.

It provides efficient multi-dimensional array objects and various operations to work with these array objects.

In this post, you learn about 1.

Installing NumPy2.

Creating arrays in NumPy3.

Basic operations on NumPy arraysInstalling NumpyMac and Linux users can install NumPy via pip command:pip install numpy2.

Since windows does not have any package manager like that in linux or mac, so you can download NumPy from here.

Once you’ve downloaded appropriate .

whl file from the link, open up the command prompt.

Navigate to the directory where you’ve downloaded the .

whl file.

Finally install it using the command:pip install name_of_the_file.

whlNote: If you are working on Anaconda, you do not need to install NumPy as it is already installed with Anaconda.

Nevertheless you can install any package/library in Anaconda via command:conda install name_of_the_package# conda install numpyTo use Numpy library in our program all you need to do in to import it.

import numpy as npIntroduction to arrays in NumPyA NumPy array is homogeneous grid of values.

In NumPy dimensions of array are called axes.

The number of axes is called rank.

A tuple of non-negative integers giving the size of the array along each dimension is called its shape.

For example consider the 2D array below.

[[11, 9, 114] [6, 0, -2]]This array has 2 axes.

First axis of length 2 and second axis of length 3.

Rank = Number of axes = 2.

Shape can be expressed as : (2, 3).

Creating arrays in NumPyTo create an array, you can use array method of numpy.

# Creating 1D arraya = np.

array([1, 2, 3])# Creating 2D arrayb = np.

array([[1,2,3],[4,5,6]])Functions to create NumPy arrays:a = np.

zeros((2,2)) # Create an array of all zerosb = np.

ones((1,2)) # Create an array of all onespi = 3.

14c = np.

full((2,2), pi) # Create a constant array of pid = np.

eye(3) # Creates a 3×3 identity matrixe = np.


random((2,2)) # Create an array of random valuesTo create sequences of numbers, NumPy provides a function analogous to range that returns arrays instead of lists.

arange: returns evenly spaced values within a given interval.

step size is specified.

linspace: returns evenly spaced values within a given interval.

num no.

of elements are returned.

A = np.

arange(0, 30, 5) # Creates [ 0, 5, 10, 15, 20, 25]B = np.

linspace(1, 15, 3) # Creates [ 1.

0, 8.

0, 15.

0]You can use reshape method to reshape an array.

Consider an array with shape (a1, a2, a3, …, aN).

We can reshape and convert it into another array with shape (b1, b2, b3, ….

, bM).

The only condition is that : (a1 *a2 * a3 ….

* aN) = (b1 *b2 * b3 ….

* bM )i.

e Number of elements in both the arrays must be same.

Accessing array elements : SlicingJust like Python lists, NumPy arrays can be sliced.

Since arrays may be multidimensional, you must specify a slice for each dimension of the array.

For examplea = np.

array([[1,2,3,4], [5,6,7,8], [9,10,11,12]])This will create an array like shown below[[1 2 3 4] [5 6 7 8] [9 10 11 12]]Now let’s say you want to access element from it.

# Accessing an elementb = a[rowIndex, colIndex]# Accessing a block of elements togetherc = a[start_row_index:end_row_index, start_col_index:end_col_index]Note 1: Index in Python starts with 0.

Note 2: Whenever we specify block of elements as start_row_index:end_row_index then it means [start_row_index, end_row_index)Basic operations on NumPy arraysBasic Arithemetic Operations# Create a dummy array for operationsa = np.

array([1, 2, 5, 3])# Add 3 to every elementa += 3# Subtract 5 from every elementa -= 5# Multiply each element by 7a *= 7# Divide each element by 6a /= 6# Squaring each elementa **= 2# Taking transposea = a.

TFew other useful functions# Create a dummy arrayarr = np.

array([[1, 5, 6], [4, 7, 2], [3, 1, 9]])# maximum element of arrayprint(arr.

max())# row-wise maximum elementsarr.

max(axis=1)# column wise minimum elementsarr.

min(axis=0)# sum of all array elementsarr.

sum()# sum of each rowarr.

sum(axis=1)# cumulative sum along each rowarr.

cumsum(axis=1)Operations on two NumPy arraysa = np.

array([[1, 2], [3, 4]])b = np.

array([[4, 3], [2, 1]])print(a+b) # [[5, 5], [5, 5]]print(a-b) # [[-3, -1], [1, 3]]print(a*b) # [[4, 6], [6, 4]]print(a.

dot(b)) # [[8, 5], [20, 13]]NumPy provides a lot of mathematical functions such as sin, cos, exp, etc.

These functions also operate elementwise on an array, producing an array as output.

a = np.

array([0, np.

pi/2, np.


sin(arr)) # sin of each elementprint(np.

cos(arr)) # cosine of each elementprint(np.

sqrt(arr)) # square root of each elementprint(np.

exp(arr)) # exponentials of each elementprint(np.

log(arr)) # log of each elementprint(np.

sum(arr)) # Sum of elementsprint(np.

std(arr)) # standard deviationSorting arrays in NumPya = np.

array([[1, 4, 2], [3, 4, 6], [0, -1, 5]])# array elements in sorted orderprint(np.

sort(a, axis=None))# sort array row wiseprint(np.

sort(a, axis=1))So that’s it for NumPy.

We’ve covered a lot of important concepts.

I hope it gives you a lot of clarity.

.. More details

Leave a Reply