support Click to see our new support page.
support For sales enquiry!

Python NumPy

Python NumPy

IjasAug. 25, 2019

Library for the Python programming language

Python has several modules. NumPy is one of its type. It is a module in python. The name is an acronym for "Numeric Python" or "Numerical Python". It is an extension module for Python, mostly written in C. This makes sure that the precompiled mathematical and numerical functions and functionalities of Numpy guarantee great execution speed, implementing multi-dimensional arrays and also matrices. These data structures guarantee efficient calculations with matrices and arrays. Like NumPy there is another module in python name as SciPy or scientific python. SciPy needs Numpy, as it is based on the data structures of Numpy and furthermore its basic creation and manipulation functions.

Both NumPy and SciPy are not part of a basic Python installation. They will be install after the Python installation. NumPy has to be installed before installing SciPy.


Python NumPy Install :

Take your terminal and type this command.

pipe install

pythonnumpy installation

Advantages of using Numpy with Python:

  • Array oriented computing.
  • Efficiently implemented multi-dimensional arrays.
  • Designed for scientific computation.

Array in python NumPy:

NumPys main object is the homogeneous multidimensional array.

  • It is a table of elements (usually numbers), all of the same type, indexed by a tuple of positive integers.
  • In NumPy dimensions are called axes. The number of axes is rank.
  • NumPys array class is called ndarray. It is also known by the alias array.


NumPy Example:

python NumpyProgram


pythonnumpy output

Array Creation in python NumPy:

Array created using passed list:

python Numpyarraycreatecode


pythonnumpyarrayusing listop

Array created using passed tuple:

create array tuple


output of array using tuple

Creation of Arrays with Evenly Spaced Values:


The syntax of arange:

arange([start,]stop[, step], [, dtype=None])

It is similar to the python built in function range. Arrange returns evenly spaced values within a given interval. The values are generated within the half-open interval '[start,stop)'. The function is used with integers. But
arrange returns an ndarray rather than a list iterator as range does. If the 'start' parameter is not given, it will be set to 0. The end of the interval is determined by the parameter 'stop'. The spacing between two adjacent values of the output array is set with the optional parameter 'step'. The default value for 'step' is 1.



Output of arrange

Linspace :

The syntax of linspace:

linspace(start,stop, num=50, endpoint=True, retstep=False)

Linspace returns an ndarray, consisting of 'num' equally spaced samples in the closed interval [start, stop] or the half-open interval [start,stop). If a closed or a half open interval will be returned, depends on whether 'endpoint' is True or False. The parameter 'start' defines the start value of the sequence which will be created. 'stop' will be the end value of the sequence, unless 'endpoint' is set to False. 'endpoint' is set to True (the default), 'stop' will be the last sample of the sequence. If the optional parameter 'retstep' is set, the function will also return the value of the spacing between adjacent values.




Reshaping array:

We 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 required condition is:
a1 x a2 x a3 … x aN = b1 x b2 x b3 … x bM. (i.e original size of array remains unchanged.)

python Numpyreshapeprogram


output reshaping

Flatten array:

We can use flatten method to get a copy of array collapsed into one dimension.

python Numpy flatten array


flatten output

Array with zeros:

python Numpyarray with zeroes



Array Indexing and Slicing:

Contents of ndarray object is access and modify by indexing or slicing. That is, just like Python's in-built container objects.


Just like lists in python, NumPy arrays can be sliced. As arrays can be multidimensional, you need to specify a slice for each dimension of the array.

Integer array indexing:

In this method, lists will be passing for indexing each dimension. One to one mapping of corresponding elements is done to construct a new arbitrary array.

Boolean array indexing:

This method is used when we want to pick elements from array which satisfy some condition.

indexingpython Numpyprogram


python Numpyindexoutput


NumPy supports a much more variety of numerical types than Python does. The following table shows different scalar data types defined in NumPy.


Data Type Objects (dtype)

The data type object 'dtype' is an instance of numpy.dtype class. It will be create with Numpy.dtype. A data type object describes interpretation of fixed block of memory corresponding to an array, depending on the following aspects :

  • Type of data (integer, float or Python object).
  • Size of data.
  • Byte order (little-endian or big-endian).
  • In case of structured type, the names of fields, data type of each field and part of the memory block taken by each field.
  • If data type is a subarray, its shape and data type.

The byte order is decided by prefixing '<' or '>' to data type. '<' means that encoding is little-endian (least significant is stored in smallest address). '>' means that encoding is big-endian (most significant byte is stored in smallest address).

A dtype object is construct using the following syntax −

numpy.dtype(object, align, copy)

The parameters are −

  • Object − That will be convert to data type object.
  • Align − If true, adds padding to the field to make it similar to C-struct.
  • Copy − Makes a new copy of dtype object. If false, the result is reference to builtin data type object.




Each built-in data type has a character code that uniquely identifies it.

  • 'b' − boolean
  • 'i' − (signed) integer
  • 'u' − unsigned integer
  • 'f' − floating-point
  • 'c' − complex-floating point
  • 'm' − timedelta'M' − datetime
  • 'O' − (Python) objects
  • 'S', 'a' − (byte-)string
  • 'U' − Unicode
  • 'V' − raw data (void)

Overview of Basic Python Numpy Operations:

Once you have created the arrays, you can do basic Numpy operations.

Operations on a 1d array:

Using Arithmetic Operators with Python Numpy

  • Let’s look at a one-dimensional array. I have 2 arrays, array1 and array2, created through two different techniques:

numpy arithmetic operatorspgm



  • You can also perform arithmetic operations on these arrays. For example, if you add the arrays, the arithmetic operator will work element-wise. The output will be an array of the same dimension.

arithmetic operator



  • You can also run an arithmetic operation on the array with a scalar value. For example, this code multiplies each element of the array by 2.



scalar-value- op

  • To find the square of the numbers, use **.

sqaureof numbers


sqaureof numbersop

  • If you would like to cube the individual elements, or even higher up, use the power function. Here, each element of the array is raise to the power 3.

cubing program





Using Python Numpy with Conditional Expressions

  • You can also use conditionals to find the values that match your criteria. Since array1 is an array, the result of a conditional operation is also an array. When we perform a conditional check, the output is an array of booleans.

conditional expression





Operations on a 2d array:

Arithmetic Operators with Python Numpy 2D Arrays

  • Let’s create 2 two-dimensional arrays, A and B.


Now, let’s try adding the arrays. Unsurprisingly, the elements at the respective positions in the arrays will be add together.

twodimensionformpython Numpy


twodimensionoutputpython Numpy

All the arithmetic operations work in a similar way. You can also multiply or divide the arrays.

Matrix Multiplication:

To perform a typical matrix multiplication (or matrix product), you can use the operator ‘@.’

matrixmultiplicationpython Numpy


matrixmultiplicationoutputpython Numpy

This is how it works: the cell (1,1) (value: 13) in the output is a Sum-Product of Row 1 in matrix A (a two-dimensional array A) and Column 1 in matrix B.

Similarly, the cell (1,2) in the output is a Sum-Product of Row 1 in matrix A and Column 2 in matrix B.

And so on, the values will be populating for all the cells.

Arithmetic Functions in Python Numpy

Next, let’s use the random function to generate a two-dimensional array.

randomfnpython Numpy


randomfnoutputpython Numpy

There are several functions that you can use to perform arithmetic operations on this array. For example, the sum function adds all the values in the array and gives a scalar output.

scalarfnpython Numpy


scalarfnoutputpython Numpy

The min function finds the lowest value in the array.

minfunpython Numpy


minfunoutputpython Numpy

Logical Operators in Python Numpy

Numpy also provides logic functions like logical_and, logical_or etc., in a similar pattern to perform logical operations.


logicaland operator


python Numpy- logical and operatorop


 python Numpylogicaloroperator


  python Numpylogicaloroperatorop

In addition to arithmetic operators, Numpy also provides functions to perform arithmetic operations. You can use functions like add, subtract, multiply, divide in order to perform array operations.


LinkedIn LinkedIn

Leave a Comment