In this Numpy Tutorial, we will learn how to install numpy library in python, numpy multidimensional arrays, numpy datatypes, numpy mathematical operation on these multidimensional arrays, and different functionalities of Numpy library.

What is Numpy?

Numpy is a Python library that supports multi-dimensional arrays and matrix. It also provides many basic and high-level mathematical functions that can be applied on these multi-dimensional arrays and matrices with less code footprint.

Why Numpy?

There are many reasons why Numpy package has been used by data scientist and analysts, machine learning experts, deep learning libraries, etc. We will go through some of the most basic advantages of Numpy over regular lists or arrays in Python.

  • The code that involves arrays with Numpy package is precise to apply transformations or operations for each element of the multidimensional arrays unlike a Python List.
  • Since n-dimensional arrays of Numpy use a single datatype and contiguous memory for storage, they take relatively lesser memory read and write times.
  • The most useful features of Numpy package is the compact datatypes that it offers, like unsigned integers of 8 bits, 16 bits size and signed integers of different bit sizes, different floating point precisions, etc.

Numpy Tutorial

Numpy Tutorial

Install Numpy

To install Numpy and all the dependencies, use pip and run the following command.

Assuming that pip is installed in your computer, open command prompt or terminal and run the following command.

In command prompt

All the libraries and their dependencies will be downloaded and installed one by one.

At the end of the command prompt output, you would see the following text.

Check Numpy Installation

To check if numpy is installed or not, open Python terminal and run the following commands.

The import statement imports the numpy library, while the print statement prints Numpy version installed.

Command Prompt Output

Numpy is installed and the same is verified by printing Numpy’s version number.

Update Numpy

You can update numpy with pip using the following command.

Numpy Datatypes

Choosing a numpy datatype for your multidimensional array is very important. If an appropriate datatype is chosen based on the requirement and data characteristics, then it can ease a large amount of memory and ofcourse the array operations can be faster.

Data typeDescription
bool_Boolean (True or False) stored as a byte
int_Default integer type (same as C long; normally either int64 or int32)
intcIdentical to C int (normally int32 or int64)
intpInteger used for indexing (same as C ssize_t; normally either int32 or int64)
int8Byte (-128 to 127)
int16Integer (-32768 to 32767)
int32Integer (-2147483648 to 2147483647)
int64Integer (-9223372036854775808 to 9223372036854775807)
uint8Unsigned integer (0 to 255)
uint16Unsigned integer (0 to 65535)
uint32Unsigned integer (0 to 4294967295)
uint64Unsigned integer (0 to 18446744073709551615)
float_Shorthand for float64.
float16Half precision float: sign bit, 5 bits exponent, 10 bits mantissa
float32Single precision float: sign bit, 8 bits exponent, 23 bits mantissa
float64Double precision float: sign bit, 11 bits exponent, 52 bits mantissa
complex_Shorthand for complex128.
complex64Complex number, represented by two 32-bit floats (real and imaginary components)
complex128Complex number, represented by two 64-bit floats (real and imaginary components)

In this Numpy Tutorial, we will use some of these datatypes, and whenever appropriate, we shall explain why a particular datatype is selected.

Import Numpy

We have already used import numpy statement while verifying the installation of numpy package using pip. This import is like any python package import. To use the functions of numpy, the package has to be imported at the start of the program.

The syntax of importing numpy package is:

Python community usally uses the numpy package with an alias np.

Now, you can use np to call all numpy functions. Going further, we will use this numpy alias version np in code for numpy.

Create a Basic One-dimensional Numpy Array

There are many ways to create an array using numpy. We go through each one of them with examples.

  1. array() np.array() function accepts a list and creates a numpy array.
  2. arange() Note that its not arrange but a range. numpy.arange function acceps the starting and ending elements of a range, followed by the interval. In the above example, 1 is the starting of the range and 15 is the ending but 15 is excluded. The interval is 2 and therefore the interval between adjacent elements of the array is 2.
  3. linspace() This function creates a floating point array with linearly spaced values. numpy.linspace() function accepts starting and ending elements of the array, followed by number of elements. In the above example, 1 is the starting, 15 is the ending and 7 is the number of elements in the array.

Create Two Dimensional Numpy Array

In the previous section, we have learned to create a one dimensional array. Now we will take a step forward and learn how to reshape this one dimensional array to a two dimensional array.

numpy.reshape() is the method used to reshape an array. reshape() function takes shape or dimension of the target array as the argument. In the following example the shape of target array is (3, 2). As we are creating a 2D array, we provided only two values in the shape. You can provide multiple dimensions as required in the shape, separated by comma.

The product of number of rows and number of columns should equal the size of the array. If the product of dimensions and the size of the array do not match, you will get an error as shown below:

Now the array a is of shape [3,2]. You can reshape this to [2,3] or [1,6] by simply calling the reshape function on the array a.

In this Numpy Tutorial, we will go through some of the functions numpy provide to create and empty N-Dimensional array and initialize it zeroes, ones or some random values.

Create Numpy Array with all zeros

If you would like to create a numpy array of a specific size with all elements initialized to zero, you can use zeros() function. The zeros() function takes the shape of the array as argument.

The default datatype of each element in the numpy array of zeros is numpy.float64.

You can change the datatype of the elements by providing dtype argument to the zeros function. Let us change to the datatype numpy.int16.

Observe that the datatype int16 belongs to numpy package, hence np.int16.

Create Numpy Array with all ones

Similar to zeros() function, we have ones() function in numpy package. It creates ones with the specified array shape.

The default datatype for each element of the array is numpy.float64. You can change this to another numpy datatype, by providing the dtype argument.

The datatype of the array created in the above example is numpy.uint8.

Create Numpy Array with random values

You can create an array with random values and specific dimensions using random function.

In the above example, there are two random keywords. The first random is the sub-package of numpy, while second random is the function. There are other functions like randint(), etc., used to create array with random integers picked from a specific range.

Numpy Array Size

Array size is independent of its shape or dimensions. size pointer returns the total number of elements in the array.

The returned value is of type int.

Numpy Array Shape

You can get the shape or dimensions of the array using shape pointer to the array.

The example holds good for any dimensional array. Let us create a four dimensional array and find its shape.

Individual values of the shape can be accessed using index.

Numpy Array level Relational Operators

In this section, you can glimpse the power of Numpy. You can apply relational operators to the whole array in a single statement.

In the following example, we have an array a, and we will check if each element of the array is greater than 4.

The output of a<5 is another array with the same shape of a, but with the boolean values representing if the element is less than 5.

Numpy Array level Arithmetic Operators

You can perform Arithmetic Operations as well at array level with ease and less code.

For example, if a is a numpy array, then

  • a/4 divides all the elements of the array with 4 and returns the resulting array.
  • a*3 multiplies all the elements of the array with 3 and returns the resulting array.

In the following example, we add 4 to each of the element in numpy array a using a single statement.

Note that the arithmetic operator returns the resulting array, but does not modify the actual array. To modify the actual array, you have to use the modifier operators like +=, /=, *=, etc.

Numpy Mathematical Functions

While introducing numpy to you, we have gone through the point that Numpy is created for Numerical Analysis in Python. Hence, you might expect that Numpy provides a huge collection of Mathematical Functions. And it is true. Numpy provides statistical functions, trigonometric functions, linear algebra functions, etc.

In this Numpy Tutorial, we will go through some of the basic mathematical functions provided by Numpy.

Numpy Sum Function – numpy.sum()

In this example, we will take an array and find the sum of the elements in it. numpy.sum() function not only allows us to calculate the sum of all elements in the array, but also along a specific axis as well.

Numpy Mean Function – numpy.mean()

In this example, we will take an array and find the mean. Mean is the average of elements of an array. numpy.mean() function not only allows us to calculate the mean of the complete array, but also along a specific axis as well.

List of all Numpy Functions

The list of all Numpy functions is vast and would make you feel that this Numpy Tutorial is on an infinite scroll. So, please refer this link: [].

Python Example for some of the regularly used Numpy Functions