Download as pdf or txt
Download as pdf or txt
You are on page 1of 53

16:49 09/05/2024 Python Num Py Tutorial - numpy

Python NumPy Tutorial


Our Python NumPy Tutorial provides the basic and advanced concepts of
the NumPy. Our NumPy tutorial is designed for beginners and
professionals.

NumPy stands for numeric python which is a python package for the
computation and processing of the multidimensional and single
dimensional array elements.

What is NumPy
NumPy stands for numeric python which is a python package for the
computation and processing of the multidimensional and single
dimensional array elements.

Travis Oliphant created NumPy package in 2005 by injecting the


features of the ancestor module Numeric into another module Numarray.

It is an extension module of Python which is mostly written in C. It


provides various functions which are capable of performing the numeric
computations with a high speed.

NumPy provides various powerful data structures, implementing multi-


dimensional arrays and matrices. These data structures are used for the
optimal computations regarding arrays and matrices.

In this tutorial, we will go through the numeric python library NumPy.

The need of NumPy


With the revolution of data science, data analysis libraries like NumPy,
SciPy, Pandas, etc. have seen a lot of growth. With a much easier syntax
than other programming languages, python is the first choice language for
the data scientist.

NumPy provides a convenient and efficient way to handle the vast amount
of data. NumPy is also very convenient with Matrix multiplication and data
reshaping. NumPy is fast which makes it reasonable to work with a large
set of data.

There are the following advantages of using NumPy for data analysis.

1. NumPy performs array-oriented computing.


2. It efficiently implements the multidimensional arrays.
3. It performs scientific computations.

about:blank 1/53
16:49 09/05/2024 Python Num Py Tutorial - numpy

4. It is capable of performing Fourier Transform and reshaping the data


stored in multidimensional arrays.
5. NumPy provides the in-built functions for linear algebra and random
number generation.

Nowadays, NumPy in combination with SciPy and Mat-plotlib is used as


the replacement to MATLAB as Python is more complete and easier
programming language than MATLAB.

NumPy Environment Setup


NumPy doesn't come bundled with Python. We have to install it using the
python pip installer. Execute the following command.

1. $ pip install numpy

It is best practice to install NumPy with the full SciPy stack. The binary
distribution of the SciPy stack is specific to the operating systems.

Windows
On the Windows operating system, The SciPy stack is provided by the
Anaconda which is a free distribution of the Python SciPy package.

It can be downloaded from the official website:


https://www.anaconda.com/. It is also available for Linux and Mac.

The CanoPy also comes with the full SciPy stack which is available as free
as well as commercial license. We can download it by visiting the link:
https://www.enthought.com/products/canopy/

The Python (x, y) is also available free with the full SciPy distribution.
Download it by visiting the link: https://python-xy.github.io/

Linux
In Linux, the different package managers are used to install the SciPy
stack. The package managers are specific to the different distributions of
Linux. Let's look at each one of them.

Ubuntu
Execute the following command on the terminal.

1. $ sudo apt-get install python-numpy

about:blank 2/53
16:49 09/05/2024 Python Num Py Tutorial - numpy

2.
3. $ python-scipy python-matplotlibipythonipythonnotebook python-
pandas
4.
5. $ python-sympy python-nose

NumPy Ndarray
Ndarray is the n-dimensional array object defined in the numpy which
stores the collection of the similar type of elements. In other words, we
can define a ndarray as the collection of the data type (dtype) objects.

The ndarray object can be accessed by using the 0 based indexing. Each
element of the Array object contains the same size in the memory.

Creating a ndarray object


The ndarray object can be created by using the array routine of the
numpy module. For this purpose, we need to import the numpy.

1. >>> a = numpy.array

Consider the below image.

We can also pass a collection object into the array routine to create the
equivalent n-dimensional array. The syntax is given below.

1. >>> numpy.array(object, dtype = None, copy = True, order = None,


subok = False, ndmin = 0)

about:blank 3/53
16:49 09/05/2024 Python Num Py Tutorial - numpy

The parameters are described in the following table.

S Paramete Description
N r

1 object It represents the collection object. It can be a list,


tuple, dictionary, set, etc.

2 dtype We can change the data type of the array elements by


changing this option to the specified type. The default
is none.

3 copy It is optional. By default, it is true which means the


object is copied.

4 order There can be 3 possible values assigned to this option.


It can be C (column order), R (row order), or A (any)

5 subok The returned array will be base class array by default.


We can change this to make the subclasses passes
through by setting this option to true.

6 ndmin It represents the minimum dimensions of the resultant


array.

To create an array using the list, use the following syntax.

1. >>> a = numpy.array([1, 2, 3])

To create a multi-dimensional array object, use the following syntax.

about:blank 4/53
16:49 09/05/2024 Python Num Py Tutorial - numpy

1. >>> a = numpy.array([[1, 2, 3], [4, 5, 6]])

To change the data type of the array elements, mention the name of the
data type along with the collection.

1. >>> a = numpy.array([1, 3, 5, 7], complex)

Finding the dimensions of the Array


The ndim function can be used to find the dimensions of the array.

1. >>> import numpy as np


2. >>> arr = np.array([[1, 2, 3, 4], [4, 5, 6, 7], [9, 10, 11, 23]])
3.
4. >>> print(arr.ndim)

about:blank 5/53
16:49 09/05/2024 Python Num Py Tutorial - numpy

Finding the size of each array element


The itemsize function is used to get the size of each array item. It returns
the number of bytes taken by each array element.

Consider the following example.

Example

1. #finding the size of each item in the array


2. import numpy as np
3. a = np.array([[1,2,3]])
4. print("Each item contains",a.itemsize,"bytes")

Output:

Each item contains 8 bytes.

Finding the data type of each array item


To check the data type of each array item, the dtype function is used.
Consider the following example to check the data type of the array items.

Example

1. #finding the data type of each array item


2. import numpy as np
3. a = np.array([[1,2,3]])

about:blank 6/53
16:49 09/05/2024 Python Num Py Tutorial - numpy

4. print("Each item is of the type",a.dtype)

Output:

Each item is of the type int64

Finding the shape and size of the array


To get the shape and size of the array, the size and shape function
associated with the numpy array is used.

Consider the following example.

Example

1. import numpy as np
2. a = np.array([[1,2,3,4,5,6,7]])
3. print("Array Size:",a.size)
4. print("Shape:",a.shape)

Output:

Array Size: 7
Shape: (1, 7)

Reshaping the array objects


By the shape of the array, we mean the number of rows and columns of a
multi-dimensional array. However, the numpy module provides us the way
to reshape the array by changing the number of rows and columns of the
multi-dimensional array.

The reshape() function associated with the ndarray object is used to


reshape the array. It accepts the two parameters indicating the row and
columns of the new shape of the array.

Let's reshape the array given in the following image.

about:blank 7/53
16:49 09/05/2024 Python Num Py Tutorial - numpy

Example

1. import numpy as np
2. a = np.array([[1,2],[3,4],[5,6]])
3. print("printing the original array..")
4. print(a)
5. a=a.reshape(2,3)
6. print("printing the reshaped array..")
7. print(a)

Output:

printing the original array..


[[1 2]
[3 4]
[5 6]]
printing the reshaped array..
[[1 2 3]
[4 5 6]]

Slicing in the Array


Slicing in the NumPy array is the way to extract a range of elements from
an array. Slicing in the array is performed in the same way as it is
performed in the python list.

Consider the following example to print a particular element of the array.

Example

1. import numpy as np
2. a = np.array([[1,2],[3,4],[5,6]])
3. print(a[0,1])
4. print(a[2,0])

Output:

2
5

The above program prints the 2nd element from the 0th index and
0th element from the 2nd index of the array.

Linspace

about:blank 8/53
16:49 09/05/2024 Python Num Py Tutorial - numpy

The linspace() function returns the evenly spaced values over the given
interval. The following example returns the 10 evenly separated values
over the given interval 5-15

Example

1. import numpy as np
2. a=np.linspace(5,15,10) #prints 10 values which are evenly spaced o
ver the given interval 5-15
3. print(a)

Output:

[ 5. 6.11111111 7.22222222 8.33333333 9.44444444 10.55555556


11.66666667 12.77777778 13.88888889 15. ]

Finding the maximum, minimum, and sum of the


array elements
The NumPy provides the max(), min(), and sum() functions which are used
to find the maximum, minimum, and sum of the array elements
respectively.

Consider the following example.

Example

1. import numpy as np
2. a = np.array([1,2,3,10,15,4])
3. print("The array:",a)
4. print("The maximum element:",a.max())
5. print("The minimum element:",a.min())
6. print("The sum of the elements:",a.sum())

Output:

The array: [ 1 2 3 10 15 4]
The maximum element: 15
The minimum element: 1
The sum of the elements: 35

NumPy Array Axis


A NumPy multi-dimensional array is represented by the axis where axis-0
represents the columns and axis-1 represents the rows. We can mention

about:blank 9/53
16:49 09/05/2024 Python Num Py Tutorial - numpy

the axis to perform row-level or column-level calculations like the addition


of row or column elements.

To calculate the maximum element among each column, the minimum


element among each row, and the addition of all the row elements,
consider the following example.

Example

1. import numpy as np
2. a = np.array([[1,2,30],[10,15,4]])
3. print("The array:",a)
4. print("The maximum elements of columns:",a.max(axis = 0))
5. print("The minimum element of rows",a.min(axis = 1))
6. print("The sum of all rows",a.sum(axis = 1))

Output:

The array: [[1 2 30]


[10 15 4]]
The maximum elements of columns: [10 15 30]
The minimum element of rows [1 4]
The sum of all rows [33 29]

Finding square root and standard deviation


The sqrt() and std() functions associated with the numpy array are used to
find the square root and standard deviation of the array elements
respectively.

Standard deviation means how much each element of the array varies
from the mean value of the numpy array.

about:blank 10/53
16:49 09/05/2024 Python Num Py Tutorial - numpy

Consider the following example.

Example

1. import numpy as np
2. a = np.array([[1,2,30],[10,15,4]])
3. print(np.sqrt(a))
4. print(np.std(a))

Output:

[[1. 1.41421356 5.47722558]


[3.16227766 3.87298335 2. ]]
10.044346115546242

Arithmetic operations on the array


The numpy module allows us to perform the arithmetic operations on
multi-dimensional arrays directly.

In the following example, the arithmetic operations are performed on the


two multi-dimensional arrays a and b.

Example

1. import numpy as np
2. a = np.array([[1,2,30],[10,15,4]])
3. b = np.array([[1,2,3],[12, 19, 29]])
4. print("Sum of array a and b\n",a+b)
5. print("Product of array a and b\n",a*b)
6. print("Division of array a and b\n",a/b)

Array Concatenation
The numpy provides us with the vertical stacking and horizontal stacking
which allows us to concatenate two multi-dimensional arrays vertically or
horizontally.

Consider the following example.

Example

about:blank 11/53
16:49 09/05/2024 Python Num Py Tutorial - numpy

1. import numpy as np
2. a = np.array([[1,2,30],[10,15,4]])
3. b = np.array([[1,2,3],[12, 19, 29]])
4. print("Arrays vertically concatenated\n",np.vstack((a,b)));
5. print("Arrays horizontally concatenated\n",np.hstack((a,b)))

Output:

Arrays vertically concatenated


[[ 1 2 30]
[10 15 4]
[ 1 2 3]
[12 19 29]]
Arrays horizontally concatenated
[[ 1 2 30 1 2 3]
[10 15 4 12 19 29]]

NumPy Datatypes
The NumPy provides a higher range of numeric data types than that
provided by the Python. A list of numeric data types is given in the
following table.

SN Data type Description

1 bool_ It represents the boolean value indicating true or false. It is


stored as a byte.

2 int_ It is the default type of integer. It is identical to long type in C


that contains 64 bit or 32-bit integer.

3 intc It is similar to the C integer (c int) as it represents 32 or 64-bit


int.

4 intp It represents the integers which are used for indexing.

5 int8 It is the 8-bit integer identical to a byte. The range of the


value is -128 to 127.

6 int16 It is the 2-byte (16-bit) integer. The range is -32768 to 32767.

7 int32 It is the 4-byte (32-bit) integer. The range is -2147483648 to


2147483647.

8 int64 It is the 8-byte (64-bit) integer. The range is


-9223372036854775808 to 9223372036854775807.

about:blank 12/53
16:49 09/05/2024 Python Num Py Tutorial - numpy

9 uint8 It is the 1-byte (8-bit) unsigned integer.

10 uint16 It is the 2-byte (16-bit) unsigned integer.

11 uint32 It is the 4-byte (32-bit) unsigned integer.

12 uint64 It is the 8 bytes (64-bit) unsigned integer.

13 float_ It is identical to float64.

14 float16 It is the half-precision float. 5 bits are reserved for the


exponent. 10 bits are reserved for mantissa, and 1 bit is
reserved for the sign.

15 float32 It is a single precision float. 8 bits are reserved for the


exponent, 23 bits are reserved for mantissa, and 1 bit is
reserved for the sign.

16 float64 It is the double precision float. 11 bits are reserved for the
exponent, 52 bits are reserved for mantissa, 1 bit is used for
the sign.

17 complex_ It is identical to complex128.

18 complex6 It is used to represent the complex number where real and


4 imaginary part shares 32 bits each.

19 complex1 It is used to represent the complex number where real and


28 imaginary part shares 64 bits each.

NumPy dtype
All the items of a numpy array are data type objects also known as numpy
dtypes. A data type object implements the fixed size of memory
corresponding to an array.

We can create a dtype object by using the following syntax.

1. numpy.dtype(object, align, copy)

The constructor accepts the following object.

Object: It represents the object which is to be converted to the data type.

Align: It can be set to any boolean value. If true, then it adds extra
padding to make it equivalent to a C struct.

Copy: It creates another copy of the dtype object.

about:blank 13/53
16:49 09/05/2024 Python Num Py Tutorial - numpy

Example 1

1. import numpy as np
2. d = np.dtype(np.int32)
3. print(d)

Output:

int32

Example 2

1. import numpy as np
2. d = np.int32(i4)
3. print(d)

Output:

int32

Creating a Structured data type


We can create a map-like (dictionary) data type which contains the
mapping between the values. For example, it can contain the mapping
between employees and salaries or the students and the age, etc.

Consider the following example.

Example 1

1. import numpy as np
2. d = np.dtype([('salary',np.float)])
3. print(d)

Output:

[('salary', '<="" pre="">

Example 2

1. import numpy as np
2. d=np.dtype([('salary',np.float)])
3. arr = np.array([(10000.12,),(20000.50,)],dtype=d)
4. print(arr['salary'])

about:blank 14/53
16:49 09/05/2024 Python Num Py Tutorial - numpy

Output:

[(10000.12,) (20000.5 ,)]

Numpy Array Creation


The ndarray object can be constructed by using the following routines.

Numpy.empty
As the name specifies, The empty routine is used to create an uninitialized
array of specified shape and data type.

The syntax is given below.

1. numpy.empty(shape, dtype = float, order = 'C')

It accepts the following parameters.

o Shape: The desired shape of the specified array.

o dtype: The data type of the array items. The default is the float.
o Order: The default order is the c-style row-major order. It can be set to F
for FORTRAN-style column-major order.

Example
1. import numpy as np
2. arr = np.empty((3,2), dtype = int)
3. print(arr)

Output:

[[ 140482883954664 36917984]
[ 140482883954648 140482883954648]
[6497921830368665435 172026472699604272]]

NumPy.Zeros
This routine is used to create the numpy array with the specified shape
where each numpy array item is initialized to 0.

The syntax is given below.

1. numpy.zeros(shape, dtype = float, order = 'C')

It accepts the following parameters.

about:blank 15/53
16:49 09/05/2024 Python Num Py Tutorial - numpy

o Shape: The desired shape of the specified array.

o dtype: The data type of the array items. The default is the float.
o Order: The default order is the c-style row-major order. It can be set to F
for FORTRAN-style column-major order.

Example
1. import numpy as np
2. arr = np.zeros((3,2), dtype = int)
3. print(arr)

Output:

[[0 0]
[0 0]
[0 0]]

NumPy.ones
This routine is used to create the numpy array with the specified shape
where each numpy array item is initialized to 1.

The syntax to use this module is given below.

1. numpy.ones(shape, dtype = none, order = 'C')

It accepts the following parameters.

o Shape: The desired shape of the specified array.

o dtype: The data type of the array items.


o Order: The default order is the c-style row-major order. It can be set to F
for FORTRAN-style column-major order.

Example
1. import numpy as np
2. arr = np.ones((3,2), dtype = int)
3. print(arr)

Output:

[[1 1]
[1 1]
[1 1]]

about:blank 16/53
16:49 09/05/2024 Python Num Py Tutorial - numpy

Numpy array from existing data


NumPy provides us the way to create an array by using the existing data.

numpy.asarray
This routine is used to create an array by using the existing data in the
form of lists, or tuples. This routine is useful in the scenario where we
need to convert a python sequence into the numpy array object.

The syntax to use the asarray() routine is given below.

1. numpy.asarray(sequence, dtype = None, order = None)

It accepts the following parameters.

1. sequence: It is the python sequence which is to be converted into the


python array.

2. dtype: It is the data type of each item of the array.

3. order: It can be set to C or F. The default is C.

Example: creating numpy array using the list


1. import numpy as np
2. l=[1,2,3,4,5,6,7]
3. a = np.asarray(l);
4. print(type(a))
5. print(a)

Output:

<class 'numpy.ndarray'>
[1 2 3 4 5 6 7]

Example: creating a numpy array using Tuple


1. import numpy as np
2. l=(1,2,3,4,5,6,7)
3. a = np.asarray(l);
4. print(type(a))
5. print(a)

Output:

<class 'numpy.ndarray'>

about:blank 17/53
16:49 09/05/2024 Python Num Py Tutorial - numpy

[1 2 3 4 5 6 7]

Example: creating a numpy array using more than one list


1. import numpy as np
2. l=[[1,2,3,4,5,6,7],[8,9]]
3. a = np.asarray(l);
4. print(type(a))
5. print(a)

Output:

<class 'numpy.ndarray'>
[list([1, 2, 3, 4, 5, 6, 7]) list([8, 9])]

numpy.frombuffer
This function is used to create an array by using the specified buffer. The
syntax to use this buffer is given below.

1. numpy.frombuffer(buffer, dtype = float, count = -1, offset = 0)

It accepts the following parameters.

o buffer: It represents an object that exposes a buffer interface.

o dtype: It represents the data type of the returned data type array. The
default value is 0.
o count: It represents the length of the returned ndarray. The default value
is -1.
o offset: It represents the starting position to read from. The default value
is 0.

Example
1. import numpy as np
2. l = b'hello world'
3. print(type(l))
4. a = np.frombuffer(l, dtype = "S1")
5. print(a)
6. print(type(a))

Output:

<class 'bytes'>

about:blank 18/53
16:49 09/05/2024 Python Num Py Tutorial - numpy

[b'h' b'e' b'l' b'l' b'o' b' ' b'w' b'o' b'r' b'l' b'd']
<class 'numpy.ndarray'>

numpy.fromiter
This routine is used to create a ndarray by using an iterable object. It
returns a one-dimensional ndarray object.

The syntax is given below.

1. numpy.fromiter(iterable, dtype, count = - 1)

It accepts the following parameters.

1. Iterable: It represents an iterable object.


2. dtype: It represents the data type of the resultant array items.
3. count: It represents the number of items to read from the buffer in the
array.

Example
1. import numpy as np
2. list = [0,2,4,6]
3. it = iter(list)
4. x = np.fromiter(it, dtype = float)
5. print(x)
6. print(type(x))

Output:

[0. 2. 4. 6.]
<class 'numpy.ndarray'>

Numpy Arrays within the numerical range


This section of the tutorial illustrates how the numpy arrays can be
created using some given specified range.

Numpy.arrange
It creates an array by using the evenly spaced values over the given
interval. The syntax to use the function is given below.

1. numpy.arrange(start, stop, step, dtype)

about:blank 19/53
16:49 09/05/2024 Python Num Py Tutorial - numpy

It accepts the following parameters.

1. start: The starting of an interval. The default is 0.


2. stop: represents the value at which the interval ends excluding this value.

3. step: The number by which the interval values change.

4. dtype: the data type of the numpy array items.

group

Example
1. import numpy as np
2. arr = np.arange(0,10,2,float)
3. print(arr)

Output:

[0. 2. 4. 6. 8.]

Example
1. import numpy as np
2. arr = np.arange(10,100,5,int)
3. print("The array over the given range is ",arr)

Output:

The array over the given range is [10 15 20 25 30 35 40 45 50 55 60 65 70


75 80 85 90 95]

NumPy.linspace
It is similar to the arrange function. However, it doesn?t allow us to specify
the step size in the syntax.

Instead of that, it only returns evenly separated values over a specified


period. The system implicitly calculates the step size.

The syntax is given below.

1. numpy.linspace(start, stop, num, endpoint, retstep, dtype)

It accepts the following parameters.

1. start: It represents the starting value of the interval.

2. stop: It represents the stopping value of the interval.

about:blank 20/53
16:49 09/05/2024 Python Num Py Tutorial - numpy

3. num: The amount of evenly spaced samples over the interval to be


generated. The default is 50.

4. endpoint: Its true value indicates that the stopping value is included in
the interval.
5. rettstep: This has to be a boolean value. Represents the steps and
samples between the consecutive numbers.
6. dtype: It represents the data type of the array items.

Example
1. import numpy as np
2. arr = np.linspace(10, 20, 5)
3. print("The array over the given range is ",arr)

Output:

The array over the given range is [10. 12.5 15. 17.5 20.]

Example
1. import numpy as np
2. arr = np.linspace(10, 20, 5, endpoint = False)
3. print("The array over the given range is ",arr)

Output:

The array over the given range is [10. 12. 14. 16. 18.]

numpy.logspace
It creates an array by using the numbers that are evenly separated on a
log scale.

The syntax is given below.

1. numpy.logspace(start, stop, num, endpoint, base, dtype)

It accepts the following parameters.

1. start: It represents the starting value of the interval in the base.

2. stop: It represents the stopping value of the interval in the base.

3. num: The number of values between the range.

about:blank 21/53
16:49 09/05/2024 Python Num Py Tutorial - numpy

4. endpoint: It is a boolean type value. It makes the value represented by


stop as the last value of the interval.

5. base: It represents the base of the log space.

6. dtype: It represents the data type of the array items.

Example
1. import numpy as np
2. arr = np.logspace(10, 20, num = 5, endpoint = True)
3. print("The array over the given range is ",arr)

Output:

The array over the given range is [1.00000000e+10 3.16227766e+12


1.00000000e+15 3.16227766e+17
1.00000000e+20]

Example
1. import numpy as np
2. arr = np.logspace(10, 20, num = 5,base = 2, endpoint = True)
3. print("The array over the given range is ",arr)

Output:

The array over the given range is [1.02400000e+03 5.79261875e+03


3.27680000e+04 1.85363800e+05
1.04857600e+06]

NumPy Broadcasting
In Mathematical operations, we may need to consider the arrays of
different shapes. NumPy can perform such operations where the array of
different shapes are involved.

For example, if we consider the matrix multiplication operation, if the


shape of the two matrices is the same then this operation will be easily
performed. However, we may also need to operate if the shape is not
similar.

Consider the following example to multiply two arrays.

Example
1. import numpy as np
2. a = np.array([1,2,3,4,5,6,7])
3. b = np.array([2,4,6,8,10,12,14])
4. c = a*b;

about:blank 22/53
16:49 09/05/2024 Python Num Py Tutorial - numpy

5. print(c)

Output:

[ 2 8 18 32 50 72 98]

However, in the above example, if we consider arrays of different shapes,


we will get the errors as shown below.

Example
1. import numpy as np
2. a = np.array([1,2,3,4,5,6,7])
3. b = np.array([2,4,6,8,10,12,14,19])
4. c = a*b;
5. print(c)

Output:

ValueError: operands could not be broadcast together with shapes (7,) (8,)

In the above example, we can see that the shapes of the two arrays are
not similar and therefore they cannot be multiplied together. NumPy can
perform such operation by using the concept of broadcasting.

In broadcasting, the smaller array is broadcast to the larger array to make


their shapes compatible with each other.

Broadcasting Rules
Broadcasting is possible if the following cases are satisfied.

1. The smaller dimension array can be appended with '1' in its shape.
2. Size of each output dimension is the maximum of the input sizes in the
dimension.

3. An input can be used in the calculation if its size in a particular dimension


matches the output size or its value is exactly 1.
4. If the input size is 1, then the first data entry is used for the calculation
along the dimension.

Broadcasting can be applied to the arrays if the following rules are


satisfied.

1. All the input arrays have the same shape.

about:blank 23/53
16:49 09/05/2024 Python Num Py Tutorial - numpy

2. Arrays have the same number of dimensions, and the length of each
dimension is either a common length or 1.

3. Array with the fewer dimension can be appended with '1' in its shape.

Let's see an example of broadcasting.

Example
1. import numpy as np
2. a = np.array([[1,2,3,4],[2,4,5,6],[10,20,39,3]])
3. b = np.array([2,4,6,8])
4. print("\nprinting array a..")
5. print(a)
6. print("\nprinting array b..")
7. print(b)
8. print("\nAdding arrays a and b ..")
9. c = a + b;
10. print(c)

Output:

printing array a..


[[ 1 2 3 4]
[ 2 4 5 6]
[10 20 39 3]]

printing array b..


[2 4 6 8]

Adding arrays a and b ..


[[ 3 6 9 12]
[ 4 8 11 14]
[12 24 45 11]]

about:blank 24/53
16:49 09/05/2024 Python Num Py Tutorial - numpy

NumPy Array Iteration


NumPy provides an iterator object, i.e., nditer which can be used to iterate
over the given array using python standard Iterator interface.

Consider the following example.

Example
1. import numpy as np
2. a = np.array([[1,2,3,4],[2,4,5,6],[10,20,39,3]])
3. print("Printing array:")
4. print(a);
5. print("Iterating over the array:")
6. for x in np.nditer(a):
7. print(x,end=' ')

Output:

Printing array:
[[ 1 2 3 4]
[ 2 4 5 6]
[10 20 39 3]]
Iterating over the array:
1 2 3 4 2 4 5 6 10 20 39 3

Order of the iteration doesn't follow any special ordering like row-major or
column-order. However, it is intended to match the memory layout of the
array.

Let's iterate over the transpose of the array given in the above example.

Example
1. import numpy as np
2. a = np.array([[1,2,3,4],[2,4,5,6],[10,20,39,3]])
3. print("Printing the array:")
4. print(a)
5. print("Printing the transpose of the array:")
6. at = a.T
7. print(at)
8.
9. #this will be same as previous
10. for x in np.nditer(at):
11. print(print("Iterating over the array:")

about:blank 25/53
16:49 09/05/2024 Python Num Py Tutorial - numpy

12. for x in np.nditer(a):


13. print(x,end=' ')

Output:

Printing the array:


[[ 1 2 3 4]
[ 2 4 5 6]
[10 20 39 3]]
Printing the transpose of the array:
[[ 1 2 10]
[ 2 4 20]
[ 3 5 39]
[ 4 6 3]]
1 2 3 4 2 4 5 6 10 20 39 3

Order of Iteration
As we know, there are two ways of storing values into the numpy arrays:

1. F-style order

2. C-style order

Let's see an example of how the numpy Iterator treats the specific orders
(F or C).

Example
1. import numpy as np
2.
3. a = np.array([[1,2,3,4],[2,4,5,6],[10,20,39,3]])
4.
5. print("\nPrinting the array:\n")
6.
7. print(a)
8.
9. print("\nPrinting the transpose of the array:\n")
10. at = a.T
11.
12. print(at)
13.
14. print("\nIterating over the transposed array\n")
15.
16. for x in np.nditer(at):

about:blank 26/53
16:49 09/05/2024 Python Num Py Tutorial - numpy

17. print(x, end= ' ')


18.
19. print("\nSorting the transposed array in C-style:\n")
20.
21. c = at.copy(order = 'C')
22.
23. print(c)
24.
25. print("\nIterating over the C-style array:\n")
26. for x in np.nditer(c):
27. print(x,end=' ')
28.
29.
30. d = at.copy(order = 'F')
31.
32. print(d)
33. print("Iterating over the F-style array:\n")
34. for x in np.nditer(d):
35. print(x,end=' ')

Output:

Printing the array:

[[ 1 2 3 4]
[ 2 4 5 6]
[10 20 39 3]]

Printing the transpose of the array:

[[ 1 2 10]
[ 2 4 20]
[ 3 5 39]
[ 4 6 3]]

Iterating over the transposed array

1 2 3 4 2 4 5 6 10 20 39 3
Sorting the transposed array in C-style:

[[ 1 2 10]
[ 2 4 20]
[ 3 5 39]
[ 4 6 3]]

Iterating over the C-style array:

1 2 10 2 4 20 3 5 39 4 6 3 [[ 1 2 10]

about:blank 27/53
16:49 09/05/2024 Python Num Py Tutorial - numpy

[ 2 4 20]
[ 3 5 39]
[ 4 6 3]]
Iterating over the F-style array:

1 2 3 4 2 4 5 6 10 20 39 3

We can mention the order 'C' or 'F' while defining the Iterator object itself.
Consider the following example.

Example
1. import numpy as np
2.
3. a = np.array([[1,2,3,4],[2,4,5,6],[10,20,39,3]])
4.
5. print("\nPrinting the array:\n")
6.
7. print(a)
8.
9. print("\nPrinting the transpose of the array:\n")
10. at = a.T
11.
12. print(at)
13.
14. print("\nIterating over the transposed array\n")
15.
16. for x in np.nditer(at):
17. print(x, end= ' ')
18.
19. print("\nSorting the transposed array in C-style:\n")
20.
21. print("\nIterating over the C-style array:\n")
22. for x in np.nditer(at, order = 'C'):
23. print(x,end=' ')

Output:

Iterating over the transposed array

1 2 3 4 2 4 5 6 10 20 39 3
Sorting the transposed array in C-style:

Iterating over the C-style array:

about:blank 28/53
16:49 09/05/2024 Python Num Py Tutorial - numpy

1 2 10 2 4 20 3 5 39 4 6 3

Array Values Modification


We can not modify the array elements during the iteration since the op-
flag associated with the Iterator object is set to readonly.

However, we can set this flag to readwrite or write only to modify the
array values. Consider the following example.

Example
1. import numpy as np
2.
3. a = np.array([[1,2,3,4],[2,4,5,6],[10,20,39,3]])
4.
5. print("\nPrinting the original array:\n")
6.
7. print(a)
8.
9. print("\nIterating over the modified array\n")
10.
11. for x in np.nditer(a, op_flags = ['readwrite']):
12. x[...] = 3 * x;
13. print(x,end = ' ')

Output:

Printing the original array:

[[ 1 2 3 4]
[ 2 4 5 6]
[10 20 39 3]]

Iterating over the modified array

3 6 9 12 6 12 15 18 30 60 117 9

NumPy Bitwise Operators


Numpy provides the following bitwise operators.

S Operator Description
N

about:blank 29/53
16:49 09/05/2024 Python Num Py Tutorial - numpy

1 bitwise_a It is used to calculate the bitwise and operation between the corresponding
nd array elements.

2 bitwise_or It is used to calculate the bitwise or operation between the corresponding


array elements.

3 invert It is used to calculate the bitwise not the operation of the array elements.

4 left_shift It is used to shift the bits of the binary representation of the elements to
the left.

5 right_shift It is used to shift the bits of the binary representation of the elements to
the right.

bitwise_and Operation
The NumPy provides the bitwise_and() function which is used to calculate
the bitwise_and operation of the two operands.

The bitwise and operation is performed on the corresponding bits of the


binary representation of the operands. If both the corresponding bit in the
operands is set to 1, then only the resultant bit in the AND result will be
set to 1 otherwise it will be set to 0.

Example
1. import numpy as np
2.
3. a = 10
4. b = 12
5.
6. print("binary representation of a:",bin(a))
7. print("binary representation of b:",bin(b))
8. print("Bitwise-and of a and b: ",np.bitwise_and(a,b))

Output:

binary representation of a: 0b1010


binary representation of b: 0b1100
Bitwise-and of a and b: 8

AND Truth Table

about:blank 30/53
16:49 09/05/2024 Python Num Py Tutorial - numpy

The output of the AND result of the two bits is 1 if and only if both the bits
are 1 otherwise it will be 0.

A B AND (A, B)

0 0 0

0 1 0

1 0 0

1 1 1

bitwise_or Operator
The NumPy provides the bitwise_or() function which is used to calculate
the bitwise or operation of the two operands.

The bitwise or operation is performed on the corresponding bits of the


binary representation of the operands. If one of the corresponding bit in
the operands is set to 1 then the resultant bit in the OR result will be set
to 1; otherwise it will be set to 0.

Example
1. import numpy as np
2.
3. a = 50
4. b = 90
5. print("binary representation of a:",bin(a))
6. print("binary representation of b:",bin(b))
7. print("Bitwise-or of a and b: ",np.bitwise_or(a,b))

Output:

binary representation of a: 0b110010


binary representation of b: 0b1011010
Bitwise-or of a and b: 122

Or truth table
The output of the OR result of the two bits is 1 if one of the bits are 1
otherwise it will be 0.

about:blank 31/53
16:49 09/05/2024 Python Num Py Tutorial - numpy

A B Or (A, B)

0 0 0

0 1 1

1 0 1

1 1 1

Invert operation
It is used to calculate the bitwise not the operation of the given operand.
The 2's complement is returned if the signed integer is passed in the
function.

Consider the following example.

Example
1. import numpy as np
2.
3. arr = np.array([20],dtype = np.uint8)
4. print("Binary representation:",np.binary_repr(20,8))
5.
6. print(np.invert(arr))
7.
8. print("Binary representation: ", np.binary_repr(235,8))

Output:

Binary representation: 00010100


[235]
Binary representation: 11101011

It shifts the bits in the binary representation of the operand to the left by
the specified position. An equal number of 0s are appended from the right.
Consider the following example.

Example
1. import numpy as np
2.

about:blank 32/53
16:49 09/05/2024 Python Num Py Tutorial - numpy

3. print("left shift of 20 by 3 bits",np.left_shift(20, 3))


4.
5. print("Binary representation of 20 in 8 bits",np.binary_repr(20, 8))
6.
7. print("Binary representation of 160 in 8 bits",np.binary_repr(160,8))

Output:

left shift of 20 by 3 bits 160


Binary representation of 20 in 8 bits 00010100
Binary representation of 160 in 8 bits 10100000

Right Shift Operation


It shifts the bits in the binary representation of the operand to the right by
the specified position. An equal number of 0s are appended from the left.
Consider the following example.

Example
1. import numpy as np
2.
3. print("left shift of 20 by 3 bits",np.right_shift(20, 3))
4.
5. print("Binary representation of 20 in 8 bits",np.binary_repr(20, 8))
6.
7. print("Binary representation of 160 in 8 bits",np.binary_repr(160,8))

Output:

left shift of 20 by 3 bits 2


Binary representation of 20 in 8 bits 00010100
Binary representation of 160 in 8 bits 10100000

NumPy String Functions


NumPy contains the following functions for the operations on the arrays of
dtype string.

S Function Description
N

1 add() It is used to concatenate the corresponding array elements (strings).

about:blank 33/53
16:49 09/05/2024 Python Num Py Tutorial - numpy

2 multiply( It returns the multiple copies of the specified string, i.e., if a string 'hello' is
) multiplied by 3 then, a string 'hello hello' is returned.

3 center() It returns the copy of the string where the original string is centered with
the left and right padding filled with the specified number of fill characters.

4 capitalize It returns a copy of the original string in which the first letter of the origina
() string is converted to the Upper Case.

5 title() It returns the title cased version of the string, i.e., the first letter of each
word of the string is converted into the upper case.

6 lower() It returns a copy of the string in which all the letters are converted into the
lower case.

7 upper() It returns a copy of the string in which all the letters are converted into the
upper case.

9 split() It returns a list of words in the string.

9 splitlines( It returns the list of lines in the string, breaking at line boundaries.
)

10 strip() Returns a copy of the string with the leading and trailing white spaces
removed.

11 join() It returns a string which is the concatenation of all the strings specified in
the given sequence.

12 replace() It returns a copy of the string by replacing all occurrences of a particular


substring with the specified one.

13 decode() It is used to decode the specified string element-wise using the specified
codec.

14 encode() It is used to encode the decoded string element-wise.

numpy.char.add() method example


1. import numpy as np
2. print("Concatenating two string arrays:")

about:blank 34/53
16:49 09/05/2024 Python Num Py Tutorial - numpy

3. print(np.char.add(['welcome','Hi'], [' to Javatpoint', ' read python'] ))

Output:

Concatenating two string arrays:


['welcome to Javatpoint' 'Hi read python']

numpy.char.multiply() method example


1. import numpy as np
2. print("Printing a string multiple times:")
3. print(np.char.multiply("hello ",3))

Output:

Printing a string multiple times:


hello hello hello

numpy.char.center() method example


1. import numpy as np
2. print("Padding the string through left and right with the fill char *");
3. #np.char.center(string, width, fillchar)
4. print(np.char.center("Javatpoint", 20, '*'))

Output:

Padding the string through left and right with the fill char *
*****Javatpoint*****

numpy.char.capitalize() method example


1. import numpy as np
2. print("Capitalizing the string using capitalize()...")
3. print(np.char.capitalize("welcome to javatpoint"))

Output:

Capitalizing the string using capitalize()...


Welcome to javatpoint

numpy.char.title() method example


1. import numpy as np
2. print("Converting string into title cased version...")
3. print(np.char.title("welcome to javatpoint"))

Output:

Converting string into title cased version...

about:blank 35/53
16:49 09/05/2024 Python Num Py Tutorial - numpy

Welcome To Javatpoint

numpy.char.lower() method example


1. import numpy as np
2. print("Converting all the characters of the string into lowercase...")
3. print(np.char.lower("WELCOME TO JAVATPOINT"))

Output:

Converting all the characters of the string into lowercase...


welcome to javatpoint

numpy.char.upper() method example


1. import numpy as np
2. print("Converting all the characters of the string into uppercase...")
3. print(np.char.upper("Welcome To Javatpoint"))

Output:

Converting all the characters of the string into uppercase...


WELCOME TO JAVATPOINT

numpy.char.split() method example


1. import numpy as np
2. print("Splitting the String word by word..")
3. print(np.char.split("Welcome To Javatpoint"),sep = " ")

Output:

Splitting the String word by word..


['Welcome', 'To', 'Javatpoint']

numpy.char.splitlines() method example


1. import numpy as np
2. print("Splitting the String line by line..")
3. print(np.char.splitlines("Welcome\nTo\nJavatpoint"))

Output:

Splitting the String line by line..


['Welcome', 'To', 'Javatpoint']

numpy.char.strip() method example


1. import numpy as np
2. str = " welcome to javatpoint "
3. print("Original String:",str)

about:blank 36/53
16:49 09/05/2024 Python Num Py Tutorial - numpy

4. print("Removing the leading and trailing whitespaces from the string")


5. print(np.char.strip(str))

Output:

Original String: welcome to javatpoint


Removing the leading and trailing whitespaces from the string
welcome to javatpoint

numpy.char.join() method example


1. import numpy as np
2. print(np.char.join(':','HM'))

Output:

H:M

numpy.char.replace() method example


1. import numpy as np
2. str = "Welcome to Javatpoint"
3. print("Original String:",str)
4. print("Modified String:",end=" ")
5. print(np.char.replace(str, "Welcome to","www."))

Output:

Original String: Welcome to Javatpoint


Modified String: www. Javatpoint

numpy.char.encode() and decode() method example


1. import numpy as np
2. enstr = np.char.encode("welcome to javatpoint", 'cp500')
3. dstr =np.char.decode(enstr, 'cp500')
4. print(enstr)
5. print(dstr)

Output:

b'\xa6\x85\x93\x83\x96\x94\x85@\xa3\x96@\x91\x81\xa5\x81\xa3\x97\x96\x89\x9
5\xa3'
welcome to javatpoint

NumPy Mathematical Functions


Numpy contains a large number of mathematical functions which can be
used to perform various mathematical operations. The mathematical

about:blank 37/53
16:49 09/05/2024 Python Num Py Tutorial - numpy

functions include trigonometric functions, arithmetic functions, and


functions for handling complex numbers. Let's discuss the mathematical
functions.

Trigonometric functions
Numpy contains the trigonometric functions which are used to calculate
the sine, cosine, and tangent of the different angles in radian.

The sin, cos, and tan functions return the trigonometric ratio for the
specified angles. Consider the following example.

Example
1. import numpy as np
2. arr = np.array([0, 30, 60, 90, 120, 150, 180])
3. print("\nThe sin value of the angles",end = " ")
4. print(np.sin(arr * np.pi/180))
5. print("\nThe cosine value of the angles",end = " ")
6. print(np.cos(arr * np.pi/180))
7. print("\nThe tangent value of the angles",end = " ")
8. print(np.tan(arr * np.pi/180))

Output:

The sin value of the angles


[0.00000000e+00 5.00000000e-01 8.66025404e-01 1.00000000e+00
8.66025404e-01 5.00000000e-01 1.22464680e-16]

The cosine value of the angles


[ 1.00000000e+00 8.66025404e-01 5.00000000e-01 6.12323400e-17
-5.00000000e-01 -8.66025404e-01 -1.00000000e+00]

The tangent value of the angles [ 0.00000000e+00 5.77350269e-01


1.73205081e+00 1.63312394e+16
-1.73205081e+00 -5.77350269e-01 -1.22464680e-16]

On the other hand, arcsin(), arccos(), and arctan() functions return the
trigonometric inverse of the specified angles.

The numpy.degrees() function can be used to verify the result of these


trigonometric functions. Consider the following example.

Example
1. import numpy as np
2. arr = np.array([0, 30, 60, 90])
3. print("printing the sin values of different angles")

about:blank 38/53
16:49 09/05/2024 Python Num Py Tutorial - numpy

4.
5. sinval = np.sin(arr*np.pi/180)
6.
7. print(sinval)
8. print("printing the inverse of the sin")
9. cosec = np.arcsin(sinval)
10.
11. print(cosec)
12.
13. print("printing the values in degrees")
14. print(np.degrees(cosec))
15.
16. print("\nprinting the cos values of different angles")
17. cosval = np.cos(arr*np.pi/180)
18.
19. print(cosval)
20. print("printing the inverse of the cos")
21. sec = np.arccos(cosval)
22. print(sec)
23.
24. print("\nprinting the values in degrees")
25. print(np.degrees(sec))
26.
27. print("\nprinting the tan values of different angles")
28. tanval = np.tan(arr*np.pi/180)
29.
30. print(tanval)
31. print("printing the inverse of the tan")
32. cot = np.arctan(tanval)
33. print(cot)
34.
35. print("\nprinting the values in degrees")
36. print(np.degrees(cot))

Output:

printing the sin values of different angles


[0. 0.5 0.8660254 1. ]
printing the inverse of the sin

about:blank 39/53
16:49 09/05/2024 Python Num Py Tutorial - numpy

[0. 0.52359878 1.04719755 1.57079633]


printing the values in degrees
[ 0. 30. 60. 90.]

printing the cos values of different angles


[1.00000000e+00 8.66025404e-01 5.00000000e-01 6.12323400e-17]
printing the inverse of the cos
[0. 0.52359878 1.04719755 1.57079633]

printing the values in degrees


[ 0. 30. 60. 90.]

printing the tan values of different angles


[0.00000000e+00 5.77350269e-01 1.73205081e+00 1.63312394e+16]
printing the inverse of the tan
[0. 0.52359878 1.04719755 1.57079633]

printing the values in degrees


[ 0. 30. 60. 90.]

Rounding Functions
The numpy provides various functions that can be used to truncate the
value of a decimal float number rounded to a particular precision of
decimal numbers. Let's discuss the rounding functions.

The numpy.around() function


This function returns a decimal value rounded to a desired position of the
decimal. The syntax of the function is given below.

1. numpy.around(num, decimals)

It accepts the following parameters.

S Parameter Description
N

1 num It is the input number.

2 decimals It is the number of decimals which to which the number is to be rounded.


The default value is 0. If this value is negative, then the decimal will be
moved to the left.

Consider the following example.

about:blank 40/53
16:49 09/05/2024 Python Num Py Tutorial - numpy

Example
1. import numpy as np
2. arr = np.array([12.202, 90.23120, 123.020, 23.202])
3. print("printing the original array values:",end = " ")
4. print(arr)
5. print("Array values rounded off to 2 decimal position",np.around(arr, 2))
6. print("Array values rounded off to -1 decimal position",np.around(arr, -1))

Output:

printing the original array values: [ 12.202 90.2312 123.02 23.202 ]


Array values rounded off to 2 decimal position [ 12.2 90.23 123.02
23.2 ]
Array values rounded off to -2 decimal position [ 10. 90. 120. 20.]

The numpy.floor() function


This function is used to return the floor value of the input data which is the
largest integer not greater than the input value. Consider the following
example.

Example
1. import numpy as np
2. arr = np.array([12.202, 90.23120, 123.020, 23.202])
3. print(np.floor(arr))

Output:

[ 12. 90. 123. 23.]

The numpy.ceil() function


This function is used to return the ceiling value of the array values which
is the smallest integer value greater than the array element. Consider the
following example.

Example
1. import numpy as np
2. arr = np.array([12.202, 90.23120, 123.020, 23.202])
3. print(np.ceil(arr))

Output:

[ 13. 91. 124. 24.]

about:blank 41/53
16:49 09/05/2024 Python Num Py Tutorial - numpy

Numpy statistical functions


Numpy provides various statistical functions which are used to perform
some statistical data analysis. In this section of the tutorial, we will
discuss the statistical functions provided by the numpy.

Finding the minimum and maximum elements from


the array
The numpy.amin() and numpy.amax() functions are used to find the
minimum and maximum of the array elements along the specified axis
respectively.

Consider the following example.

Example
1. import numpy as np
2.
3. a = np.array([[2,10,20],[80,43,31],[22,43,10]])
4.
5. print("The original array:\n")
6. print(a)
7.
8.
9. print("\nThe minimum element among the array:",np.amin(a))
10. print("The maximum element among the array:",np.amax(a))
11.
12. print("\nThe minimum element among the rows of array",np.amin(a,0))
13. print("The maximum element among the rows of array",np.amax(a,0))
14.
15. print("\nThe minimum element among the columns of array",np.amin(a,1)
)
16. print("The maximum element among the columns of array",np.amax(a,1))

Output:

Advertisement

The original array:

[[ 2 10 20]

about:blank 42/53
16:49 09/05/2024 Python Num Py Tutorial - numpy

[80 43 31]
[22 43 10]]

The minimum element among the array: 2


The maximum element among the array: 80

The minimum element among the rows of array [ 2 10 10]


The maximum element among the rows of array [80 43 31]

The minimum element among the columns of array [ 2 31 10]


The maximum element among the columns of array [20 80 43]

numpy.ptp() function
The name of the function numpy.ptp() is derived from the name peak-to-
peak. It is used to return the range of values along an axis. Consider the
following example.

Example
1. import numpy as np
2.
3. a = np.array([[2,10,20],[80,43,31],[22,43,10]])
4.
5. print("Original array:\n",a)
6.
7. print("\nptp value along axis 1:",np.ptp(a,1))
8.
9. print("ptp value along axis 0:",np.ptp(a,0))

Output:

Original array:
[[ 2 10 20]
[80 43 31]
[22 43 10]]

ptp value along axis 1: [18 49 33]


ptp value along axis 0: [78 33 21]

numpy.percentile() function
The syntax to use the function is given below.

1. numpy.percentile(input, q, axis)

It accepts the following parameters.

1. input: It is the input array.

about:blank 43/53
16:49 09/05/2024 Python Num Py Tutorial - numpy

2. q: It is the percentile (1-100) which is calculated of the array element.


3. axis: It is the axis along which the percentile is to be calculated.

Consider the following example.

Example
1. import numpy as np
2.
3. a = np.array([[2,10,20],[80,43,31],[22,43,10]])
4.
5. print("Array:\n",a)
6.
7. print("\nPercentile along axis 0",np.percentile(a, 10,0))
8.
9. print("Percentile along axis 1",np.percentile(a, 10, 1))

Output:

Array:
[[ 2 10 20]
[80 43 31]
[22 43 10]]

Percentile along axis 0 [ 6. 16.6 12. ]


Percentile along axis 1 [ 3.6 33.4 12.4]

Calculating median, mean, and average of array


items
The numpy.median() function:
Median is defined as the value that is used to separate the higher range
of data sample with a lower range of data sample. The function
numpy.median() is used to calculate the median of the multi-dimensional
or one-dimensional arrays.

The numpy.mean() function:


The mean can be calculated by adding all the items of the arrays dividing
by the number of array elements. We can also mention the axis along
which the mean can be calculated.

The numpy.average() function:

about:blank 44/53
16:49 09/05/2024 Python Num Py Tutorial - numpy

The numpy.average() function is used to find the weighted average along


the axis of the multi-dimensional arrays where their weights are given in
another array.

Consider the following example.

Example
1. import numpy as np
2.
3. a = np.array([[1,2,3],[4,5,6],[7,8,9]])
4.
5. print("Array:\n",a)
6.
7. print("\nMedian of array along axis 0:",np.median(a,0))
8. print("Mean of array along axis 0:",np.mean(a,0))
9. print("Average of array along axis 1:",np.average(a,1))

NumPy Sorting and Searching


Numpy provides a variety of functions for sorting and searching. There are
various sorting algorithms like quicksort, merge sort and heapsort which is
implemented using the numpy.sort() function.

The kind of the sorting algorithm to be used in the sort operation must be
mentioned in the function call.

Let's discuss the sorting algorithm which is implemented in numpy.sort()

SN Algorithm Worst case complexity

1 Quick Sort O (n ^ 2)

2 Merge Sort O (n * log(n))

3 Heap Sort O (n * log(n))

The syntax to use the numpy.sort() function is given below.

1. numpy.sort(a, axis, kind, order)

It accepts the following parameters.

about:blank 45/53
16:49 09/05/2024 Python Num Py Tutorial - numpy

S Parameter Description
N

1 input It represents the input array which is to be sorted.

2 axis It represents the axis along which the array is to be sorted. If the axis is
not mentioned, then the sorting is done along the last available axis.

3 kind It represents the type of sorting algorithm which is to be used while


sorting. The default is quick sort.

4 order It represents the filed according to which the array is to be sorted in the
case if the array contains the fields.

Consider the following example.

Example
1. import numpy as np
2.
3. a = np.array([[10,2,3],[4,5,6],[7,8,9]])
4.
5. print("Sorting along the columns:")
6. print(np.sort(a))
7.
8. print("Sorting along the rows:")
9. print(np.sort(a, 0))
10.
11. data_type = np.dtype([('name', 'S10'),('marks',int)])
12.
13. arr = np.array([('Mukesh',200),('John',251)],dtype = data_type)
14.
15. print("Sorting data ordered by name")
16.
17. print(np.sort(arr,order = 'name'))

Output:

Sorting along the columns:


[[ 2 3 10]

about:blank 46/53
16:49 09/05/2024 Python Num Py Tutorial - numpy

[ 4 5 6]
[ 7 8 9]]
Sorting along the rows:
[[ 4 2 3]
[ 7 5 6]
[10 8 9]]
Sorting data ordered by name
[(b'John', 251) (b'Mukesh', 200)]

numpy.argsort() function
This function is used to perform an indirect sort on an input array that is, it
returns an array of indices of data which is used to construct the array of
sorted data.

Consider the following example.

Example
1. import numpy as np
2.
3. a = np.array([90, 29, 89, 12])
4.
5. print("Original array:\n",a)
6.
7. sort_ind = np.argsort(a)
8.
9. print("Printing indices of sorted data\n",sort_ind)
10.
11. sort_a = a[sort_ind]
12.
13. print("printing sorted array")
14.
15. for i in sort_ind:
16. print(a[i],end = " ")

Output:

Original array:
[90 29 89 12]
Printing indices of sorted data
[3 1 2 0]
printing sorted array
12 29 89 90

about:blank 47/53
16:49 09/05/2024 Python Num Py Tutorial - numpy

numpy.lexsort() function
This function is used to sort the array using the sequence of keys
indirectly. This function performs similarly to the numpy.argsort() which
returns the array of indices of sorted data.

Consider the following example.

Example
1. import numpy as np
2.
3. a = np.array(['a','b','c','d','e'])
4.
5. b = np.array([12, 90, 380, 12, 211])
6.
7. ind = np.lexsort((a,b))
8.
9. print("printing indices of sorted data")
10.
11. print(ind)
12.
13. print("using the indices to sort the array")
14.
15. for i in ind:
16. print(a[i],b[i])

Output:

printing indices of sorted data


[0 3 1 4 2]
using the indices to sort the array
a 12
d 12
b 90
e 211
c 380

numpy.nonzero() function
This function is used to find the location of the non-zero elements from the
array.

Consider the following example.

about:blank 48/53
16:49 09/05/2024 Python Num Py Tutorial - numpy

Example
1. import numpy as np
2.
3. b = np.array([12, 90, 380, 12, 211])
4.
5. print("printing original array",b)
6.
7. print("printing location of the non-zero elements")
8.
9. print(b.nonzero())

Output:

printing original array [ 12 90 380 12 211]


printing location of the non-zero elements
(array([0, 1, 2, 3, 4]),)

numpy.where() function
This function is used to return the indices of all the elements which
satisfies a particular condition.

Consider the following example.

Example
1. import numpy as np
2.
3. b = np.array([12, 90, 380, 12, 211])
4.
5. print(np.where(b>12))
6.
7. c = np.array([[20, 24],[21, 23]])
8.
9. print(np.where(c>20))

Output:

(array([1, 2, 4]),)
(array([0, 1, 1]), array([1, 0, 1]))

NumPy Copies and Views

about:blank 49/53
16:49 09/05/2024 Python Num Py Tutorial - numpy

The copy of an input array is physically stored at some other location and
the content stored at that particular location is returned which is the copy
of the input array whereas the different view of the same memory location
is returned in the case of view.

In this section of the tutorial, we will consider the way by which, the
different copies and views are generated from some memory location.

Array Assignment
The assignment of a numpy array to another array doesn't make the
direct copy of the original array, instead, it makes another array with the
same content and same id. It represents the reference to the original
array. Changes made on this reference are also reflected in the original
array.

The id() function returns the universal identifier of the array similar to the
pointer in C.

Advertisement

Consider the following example.

Example
1. import numpy as np
2.
3. a = np.array([[1,2,3,4],[9,0,2,3],[1,2,3,19]])
4.
5. print("Original Array:\n",a)
6.
7. print("\nID of array a:",id(a))
8.
9. b=a
10.
11. print("\nmaking copy of the array a")
12.
13. print("\nID of b:",id(b))
14.
15. b.shape = 4,3;
16.
17. print("\nChanges on b also reflect to a:")
18. print(a)

about:blank 50/53
16:49 09/05/2024 Python Num Py Tutorial - numpy

Output:

Original Array:
[[ 1 2 3 4]
[ 9 0 2 3]
[ 1 2 3 19]]

ID of array a: 139663602288640

making copy of the array a

ID of b: 139663602288640

Changes on b also reflect to a:


[[ 1 2 3]
[ 4 9 0]
[ 2 3 1]
[ 2 3 19]]

ndarray.view() method
The ndarray.view() method returns the new array object which contains
the same content as the original array does. Since it is a new array object,
changes made on this object do not reflect the original array.

Consider the following example.

Example
1. import numpy as np
2.
3. a = np.array([[1,2,3,4],[9,0,2,3],[1,2,3,19]])
4.
5. print("Original Array:\n",a)
6.
7. print("\nID of array a:",id(a))
8.
9. b = a.view()
10.
11. print("\nID of b:",id(b))
12.
13. print("\nprinting the view b")
14. print(b)
15.
16. b.shape = 4,3;
17.
18. print("\nChanges made to the view b do not reflect a")

about:blank 51/53
16:49 09/05/2024 Python Num Py Tutorial - numpy

19. print("\nOriginal array \n",a)


20. print("\nview\n",b)

Output:

Original Array:
[[ 1 2 3 4]
[ 9 0 2 3]
[ 1 2 3 19]]

ID of array a: 140280414447456

ID of b: 140280287000656

printing the view b


[[ 1 2 3 4]
[ 9 0 2 3]
[ 1 2 3 19]]

Changes made to the view b do not reflect a

Original array
[[ 1 2 3 4]
[ 9 0 2 3]
[ 1 2 3 19]]

view
[[ 1 2 3]
[ 4 9 0]
[ 2 3 1]
[ 2 3 19]]

ndarray.copy() method
It returns the deep copy of the original array which doesn't share any
memory with the original array. The modification made to the deep copy
of the original array doesn't reflect the original array.

Consider the following example.

Example
1. import numpy as np
2.
3. a = np.array([[1,2,3,4],[9,0,2,3],[1,2,3,19]])
4.
5. print("Original Array:\n",a)
6.
7. print("\nID of array a:",id(a))
8.
9. b = a.copy()

about:blank 52/53
16:49 09/05/2024 Python Num Py Tutorial - numpy

10.
11. print("\nID of b:",id(b))
12.
13. print("\nprinting the deep copy b")
14. print(b)
15.
16. b.shape = 4,3;
17.
18. print("\nChanges made to the copy b do not reflect a")
19. print("\nOriginal array \n",a)
20. print("\nCopy\n",b)

Output:

Original Array:
[[ 1 2 3 4]
[ 9 0 2 3]
[ 1 2 3 19]]

ID of array a: 139895697586176

ID of b: 139895570139296

printing the deep copy b


[[ 1 2 3 4]
[ 9 0 2 3]
[ 1 2 3 19]]

Changes made to the copy b do not reflect a

Original array
[[ 1 2 3 4]
[ 9 0 2 3]
[ 1 2 3 19]]

Copy
[[ 1 2 3]
[ 4 9 0]
[ 2 3 1]
[ 2 3 19]]

about:blank 53/53

You might also like