Tech With Tim Logo
Go back

Introduction

Numpy Module

The numpy module implements support for powerful multi-dimensional arrays. It is mostly used for scientific computing but can be useful in other scenarios.

Installation

The numpy module does not come with a default python installation and must be installed. To do this please open up command prompt and type "pip install numpy". pip-install-numpy.png

If this throws an error please follow the video above as it will show you another method to install numpy.

Using Numpy

Before we can start using numpy we must import it. Typically when we import numpy we import it as np.

import numpy as np

The simplest way to create a numpy array is to do so based on a list.

arr = np.array([1,2,3])
print(arr)  # prints array([1,2,3])

To get the shape of the array we can use:

arr.shape  # -> (3,)

Indexing

Indexing numpy arrays is slightly different lists in python. To index we use one set of square brackets with ints separated by commas.

arr = np.array([[1,2,3],[4,5,6]])
print(arr[1,1])  # -> 5

Useful Methods

To get the amount of elements in the array we can use .size.

arr = np.array([[1,2,3],[4,5,6]])
print(arr.size)  # -> 6

To see the amount of dimensions in our array we can use .ndim.

arr = np.array([[1,2,3],[4,5,6]])
print(arr.ndim)  # -> 2

To add things into our arrays we can use np.append(array, item).

arr = np.array([1,2,3])
arr = np.append(arr, 7)

print(arr)  #-> array([1,2,3,7])

To delete something from our array we can use np.delete(array, index).

arr = np.array([1,2,3])
arr = np.delete(arr, 0)

print(arr)  #-> array([2,3])
Design & Development by Ibezio Logo