Unit_V_numpy_Lastupdated
Unit_V_numpy_Lastupdated
Numpy & Pandas ==> for Data Analysis (Data Analytics ) ==> Data science
----------------------------------------------------------------------------------------------------------------------------------
Numpy: Numerical Python
----------------------------------------------------------------------------------------------------------------------------------
Numpy: ➔ Numerical Python
➢ NumPy is a library for the Python programming language, adding support for large, multi-
dimensional arrays and matrices, along with a large collection of high-level mathematical
functions to operate on these arrays.
➢ Numpy and pandas are data science libraries or API (Application Programming Interface).
What is numpy?
▪ Numpy stands for Numerical Python
▪ Numpy is python library used for working with arrays (Vectors and Matrices).
▪ Numpy provide functions to work with linear algebra, fourier transform and matrices.
❑ Array is collection of similar type data or elements.
----------------------------------------------------------------------------------------------------------------------------------
Difference between numpy Array and python traditional List
List Array
List is a collection of heterogeneous data Array is collection of homogeneous data
elements. elements.
List does not have axis or dimensions. Array is having axis or dimensions
In List data will stored as objects. In array data will stored as scalar value.
List is dynamic in size. Because of this list store Array is fixed in size. Because of this array store
data as objects it occupy more memory space. data as scalar values it occupy less memory
space.
It is not efficient to process / store large sets of It is efficient to process / store large set of data.
data.
List hold only objects types. Array holds scalar types and objects types.
Python Programming by Prof.B.Sreenivasu Sreyas Institute of Engineering and Technology (Autonomous) Hyderabad Page 1 of 77
Key points on ‘numpy’ module:
# Numpy => Numeric python => to work with numpy arrays
# Difference between traditional python list and numpy array
1. Python traditional list is heterogeneous data structure
2. Where as Numpy array is homogeneous data structure
3. Python traditional list requires more memory space (for large data sets)
4. Python numpy array requires less memory space (for large data sets)
----------------------------------------------------------------------------------------------------------------------------------
# There are different approaches for creating numpy array
1. array()
2.arnage()
3.indentity()
# syntax:
object_name=numpy.array(object,dtype)
Example programs:
# python program to create numpy array object using traditional python objects
import numpy as np
import sys
list1=[10,20,30,40,50,60,70,80,90]
print("Contents of list object is: ",list1)
print("Data type of list object is: ",type(list1))
array1=np.array(list1)
print("contents of array1: ",array1)
print("Data type of numpy array object is: ",type(array1))
# ndarray is a pre-defined class in 'numpy' module
OUTPUT:
Contents of list object is: [10, 20, 30, 40, 50, 60, 70, 80, 90]
Data type of list object is: <class 'list'>
contents of array1: [10 20 30 40 50 60 70 80 90]
Data type of numpy array object is: <class 'numpy.ndarray'>
----------------------------------------------------------------------------------------------------------------------------------
Python Programming by Prof.B.Sreenivasu Sreyas Institute of Engineering and Technology (Autonomous) Hyderabad Page 2 of 77
# numpy array object attributes (properties of numpy array objects) are:
# 1. ndim ==> dimension of 'numpy' array object => represents number of indices required to access
each of the elements of numpy array object.
# 2. shape ==> shape attribute represents rows and columns of numpy array object
# 3. size ==> Total number of elements in a numpy array object
# 4. dtype ==> data type of elements of a numpy array object Example: int8, int16, float16,float32
Example program:
# python program to create numpy array object using traditional python objects
# also to read values of attributes of a numpy array object
import numpy as np
import sys
list1=[10,20,30,40,50,60,70,80,90]
print("Contents of list object is: ",list1)
print("Data type of list object is: ",type(list1))
array1=np.array(list1)
print("contents of array1: ",array1)
print("Data type of numpy array object is: ",type(array1)) # ndarray is a pre-defined class in
'numpy' module
print("dimension of 'numpy' array object= ",array1.ndim)
print("value of shape attribute of numpy array object = ",array1.shape)
print("total number of elements in a numpy array object = ",array1.size)
print("data type of numpy array object = ",array1.dtype)
OUTPUT:
Contents of list object is: [10, 20, 30, 40, 50, 60, 70, 80, 90]
Data type of list object is: <class 'list'>
contents of array1: [10 20 30 40 50 60 70 80 90]
Data type of numpy array object is: <class 'numpy.ndarray'>
dimension of 'numpy' array object= 1
value of shape attribute of numpy array object = (9,)
total number of elements in a numpy array object = 9
data type of numpy array object = int32
----------------------------------------------------------------------------------------------------------------------------------
Python Programming by Prof.B.Sreenivasu Sreyas Institute of Engineering and Technology (Autonomous) Hyderabad Page 3 of 77
# python program to create numpy array using traditional python objects
import numpy as np
import sys
list1=[10,20,30,40,50,60,70,80,90,10,20,30,40,50,60,70,80,90,10,20,30,40,50,60,70,80,90,10,20,30,40,50,6
0,70,80,90]
print(list1,type(list1))
print("Memory space required for list object= ",sys.getsizeof(list1))
array1=np.array(list1)
print("contents of array1: ",array1, type(array1))
print("Memory space required for numpy array object= ",sys.getsizeof(array1))
print("dimension of 'numpy' array object= ",array1.ndim)
print("value of shape attribute of numpy array object = ",array1.shape)
print("total number of elements in a numpy array object = ",array1.size)
print("data type of numpy array object = ",array1.dtype)
OUTPUT:
[10, 20, 30, 40, 50, 60, 70, 80, 90, 10, 20, 30, 40, 50, 60, 70, 80, 90, 10, 20, 30, 40, 50, 60, 70, 80, 90, 10, 20,
30, 40, 50, 60, 70, 80, 90] <class 'list'>
Memory space required for list object= 344
contents of array1: [10 20 30 40 50 60 70 80 90 10 20 30 40 50 60 70 80 90 10 20 30 40 50 60
70 80 90 10 20 30 40 50 60 70 80 90] <class 'numpy.ndarray'>
Memory space required for numpy array object= 256
dimension of 'numpy' array object= 1
value of shape attribute of numpy array object = (36,)
total number of elements in a numpy array object = 36
data type of numpy array object = int32
----------------------------------------------------------------------------------------------------------------------------------
# python program to create numpy array using traditional python objects
import numpy as np
import sys
list1=[10,20,30,40,50,60,70,80,90]
print(list1,type(list1))
print("Memory space required for list object= ",sys.getsizeof(list1))
array1=np.array(list1)
print("contents of array1: ",array1, type(array1))
Python Programming by Prof.B.Sreenivasu Sreyas Institute of Engineering and Technology (Autonomous) Hyderabad Page 4 of 77
print("Memory space required for numpy array object= ",sys.getsizeof(array1))
print("dimension of 'numpy' array object= ",array1.ndim)
print("value of shape attribute of numpy array object = ",array1.shape)
print("total number of elements in a numpy array object = ",array1.size)
print("data type of numpy array object = ",array1.dtype)
OUTPUT:
[10, 20, 30, 40, 50, 60, 70, 80, 90] <class 'list'>
Memory space required for list object= 136
contents of array1: [10 20 30 40 50 60 70 80 90] <class 'numpy.ndarray'>
Memory space required for numpy array object= 148
dimension of 'numpy' array object= 1
value of shape attribute of numpy array object = (9,)
total number of elements in a numpy array object = 9
data type of numpy array object = int32
----------------------------------------------------------------------------------------------------------------------------------
# python program to create numpy array using traditional python objects
import numpy as np
import sys
list1=[10,20,30,40,50,60,70,80,90]
print(list1,type(list1))
print("Memory space required for list object= ",sys.getsizeof(list1))
array1=np.array(list1)
array1.shape=(3,3)
print("contents of array1: \n",array1, type(array1))
print("Memory space required for numpy array object= ",sys.getsizeof(array1))
print("dimension of 'numpy' array object= ",array1.ndim)
print("value of shape attribute of numpy array object = ",array1.shape)
print("total number of elements in a numpy array object = ",array1.size)
print("data type of numpy array object = ",array1.dtype)
print(array1[1][1]) # accessing individual elements of a numpy array object
Python Programming by Prof.B.Sreenivasu Sreyas Institute of Engineering and Technology (Autonomous) Hyderabad Page 5 of 77
OUTPUT:
----
[10, 20, 30, 40, 50, 60, 70, 80, 90] <class 'list'>
Memory space required for list object= 136
contents of array1:
[[10 20 30]
[40 50 60]
[70 80 90]] <class 'numpy.ndarray'>
Memory space required for numpy array object= 164
dimension of 'numpy' array object= 2
value of shape attribute of numpy array object = (3, 3)
total number of elements in a numpy array object = 9
data type of numpy array object = int32
50
----------------------------------------------------------------------------------------------------------------------------------
# python program to create numpy array using traditional python objects
import numpy as np
import sys
list1=[10,20,30,40,50,60,70,80,90]
print(list1,type(list1))
print("Memory space required for list object= ",sys.getsizeof(list1))
array1=np.array(list1)
#array2=np.reshape(array1,(3,3))
array2=array1.reshape(3,3)
print("contents of array1: \n",array2, type(array2))
print("Memory space required for numpy array object= ",sys.getsizeof(array1))
print("dimension of 'numpy' array object= ",array1.ndim)
print("value of shape attribute of numpy array object = ",array1.shape)
print("total number of elements in a numpy array object = ",array1.size)
print("data type of numpy array object = ",array1.dtype)
print(array1[1][1])
OUTPUT:
Python Programming by Prof.B.Sreenivasu Sreyas Institute of Engineering and Technology (Autonomous) Hyderabad Page 6 of 77
[10, 20, 30, 40, 50, 60, 70, 80, 90] <class 'list'>
Memory space required for list object= 136
contents of array1:
[[10 20 30]
[40 50 60]
[70 80 90]] <class 'numpy.ndarray'>
Memory space required for numpy array object= 148
dimension of 'numpy' array object= 1
value of shape attribute of numpy array object = (9,)
total number of elements in a numpy array object = 9
data type of numpy array object = int32
----------------------------------------------------------------------------------------------------------------------------------
Important concept:
# for reshaping numpy array object there are two imp approaches
1.using shape attribute
2. using reshape() function
----------------------------------------------------------------------------------------------------------------------------------
# python program to create numpy array using traditional python objects
import numpy as np
x=10
print(x,type(x))
array1=np.array(x,dtype=np.int8)
Python Programming by Prof.B.Sreenivasu Sreyas Institute of Engineering and Technology (Autonomous) Hyderabad Page 7 of 77
OUTPUT:
10 <class 'int'>
contents of array1:
10 <class 'numpy.ndarray'>
dimension of 'numpy' array object= 0
value of shape attribute of numpy array object = ()
total number of elements in a numpy array object = 1
data type of numpy array object = int8
----------------------------------------------------------------------------------------------------------------------------------
array1=np.array(s1)
OUTPUT:
array1=np.array(dict1)
OUTPUT:
OUTPUT:
Contents of numpy array is =
[ 2. 4. 6. 8. 10. 12. 14. 16. 18. 20. 22. 24. 26. 28. 30.] <class 'numpy.ndarray'>
dimension of 'numpy' array object= 1
value of shape attribute of numpy array object = (15,)
total number of elements in a numpy array object = 15
data type of numpy array object = float32
----------------------------------------------------------------------------------------------------------------------------------
Python Programming by Prof.B.Sreenivasu Sreyas Institute of Engineering and Technology (Autonomous) Hyderabad Page 10 of 77
(OR)
Download and install anaconda distribution
Anaconda is a python distribution which provides,
❖ Python software
❖ Data Science and ML Libraries
❖ Numpy
❖ Pandas
❖ Matplotlib
❖ Scipy
❖ TensorFlow
❖ ScikitLearn
❖ IDE’s (Jupiter, Spyder)
https://www.anaconda.com/products/individual
Python Programming by Prof.B.Sreenivasu Sreyas Institute of Engineering and Technology (Autonomous) Hyderabad Page 11 of 77
Python Programming by Prof.B.Sreenivasu Sreyas Institute of Engineering and Technology (Autonomous) Hyderabad Page 12 of 77
Python Programming by Prof.B.Sreenivasu Sreyas Institute of Engineering and Technology (Autonomous) Hyderabad Page 13 of 77
Python Programming by Prof.B.Sreenivasu Sreyas Institute of Engineering and Technology (Autonomous) Hyderabad Page 14 of 77
Jupyter notebook:
Jupyter notebook is a browser based IDE.
Python Programming by Prof.B.Sreenivasu Sreyas Institute of Engineering and Technology (Autonomous) Hyderabad Page 15 of 77
❑ The Jupyter Notebook is a web-based interactive computing platform. The notebook
combines live code, equations, narrative text, visualizations, ...
❖ Numpy is used to create arrays. The array object in numpy is called ndarray object
❖ (OR) ndarray is data type or class which represent array object.
❖ ndarray class is used to create array objects in python.
❖ ‘ndarray’ is pre-defined class in numpy module.
1. array()
2. arange()
3. zeros()
4. ones()
5. full()
6. eye()
7. identity()
dtype: dtype is attribute of array, which define data type, dtype that allows us to define the
expected data type of the array elements:
----------------------------------------------------------------------------------------------------------------------------------
Python Programming by Prof.B.Sreenivasu Sreyas Institute of Engineering and Technology (Autonomous) Hyderabad Page 16 of 77
Float data types
Float16 : 2bytes
Float32 : 4bytes
Float64 : 8bytes
Complex64 : 8bytes
Complex128 :16bytes
array_object =numpy.array(object,dtype,ndim)
Python Programming by Prof.B.Sreenivasu Sreyas Institute of Engineering and Technology (Autonomous) Hyderabad Page 17 of 77
Creating numpy array:
▪ Numpy is used to create arrays. The array object in numpy is called ndarray object.
▪ ndarray class is used to create array objects in python.
▪ Numpy provide various functions for creating array.
▪ array() : The function create ndarray object.
Python Programming by Prof.B.Sreenivasu Sreyas Institute of Engineering and Technology (Autonomous) Hyderabad Page 18 of 77
Q: What is dimension?
Dimension define depth of array or nested.
Dimension of an array is number of indices required to access elements of an numpy array object
Q: What is size?
The size will define total number elements exists within array
Q: What is dtype?
Type of elements hold by array
Python Programming by Prof.B.Sreenivasu Sreyas Institute of Engineering and Technology (Autonomous) Hyderabad Page 19 of 77
Syntax of array() function:
array_object =numpy.array(object,dtype,order,ndim)
Python Programming by Prof.B.Sreenivasu Sreyas Institute of Engineering and Technology (Autonomous) Hyderabad Page 20 of 77
The ‘order’ attribute of numpy array object in python is used to specify the memory layout order of
the elements in the array.
It can take two values: 'C' for C-style (row-major) order, and 'F' for Fortran-style (column-major)
order.
import numpy as np
OUTPUT:
C-style order:
[[1 2 3]
[4 5 6]
[7 8 9]]
Fortran-style order:
[[1 2 3]
[4 5 6]
[7 8 9]]
printing elements of array_c
123
456
789
printing elements of array_f
123
456
789
Python Programming by Prof.B.Sreenivasu Sreyas Institute of Engineering and Technology (Autonomous) Hyderabad Page 22 of 77
#python program to create array using empty() function
import numpy as np
arr1=np.empty(shape=(5,),dtype=np.float16)
print(arr1)
arr2=np.empty(shape=(2,2),dtype=np.float16)
print(arr2)
arr3=np.empty(shape=(3,3),dtype=np.float16)
print(arr3)
OUTPUT:
[0. 0. 0. 0. 0.]
[[0. 1.875]
[0. 1.875]]
[[0. 0. 0.]
[0. 0. 0.]
[0. 0. 0.]]
----------------------------------------------------------------------------------------------------------------------------------
Python Programming by Prof.B.Sreenivasu Sreyas Institute of Engineering and Technology (Autonomous) Hyderabad Page 23 of 77
zeros()
This function return array with zero filled values.
Syntax:
zeros(shape,dtype=float)
ones()
This function return array with ones filled values.
Syntax:
ones(shape,dtype=float)
Python Programming by Prof.B.Sreenivasu Sreyas Institute of Engineering and Technology (Autonomous) Hyderabad Page 24 of 77
asarray()
This function return array object (OR) this function is used to convert input object into array object.
Syntax:
asarray(object,dtype=None)
If the data type is not defined, it takes the data types based input object elements types.
frombuffer()
Buffer is temp storage memory area
Buffers are used to increase efficiency in read and writing.
frombuffer() function is used to construct array object using buffer. Buffer is a collection of bytes
Syntax:
frombuffer(buffer,dtype=float,count=-1,offset=0)
fromiter()
This function return numpy array object using iterator object.
Syntax:
fromiter(iterable,dtype,count=-1)
Python Programming by Prof.B.Sreenivasu Sreyas Institute of Engineering and Technology (Autonomous) Hyderabad Page 25 of 77
iterable that will provide data for one dimension array object
count represents the number of elements should read from iterable, the default is -1 which indicates
all elements.
arange()
The function return array object with numeric range of values.
Syntax:
arange(start,stop,step,dtype=None)
Python Programming by Prof.B.Sreenivasu Sreyas Institute of Engineering and Technology (Autonomous) Hyderabad Page 26 of 77
linspace()
logspace()
The logspace function create numpy array object evenly separated values using log scale.
Syntax:
logspace(start,stop,num,endpoint,base,dtype)
Python Programming by Prof.B.Sreenivasu Sreyas Institute of Engineering and Technology (Autonomous) Hyderabad Page 27 of 77
full()
numpy.full(shape, fill_value, dtype=None)
Return a new array of given shape and type, filled with fill_value.
eye()
numpy.eye(N, M=None, k=0, dtype=<class 'float'>)
Return a 2-D array with ones on the diagonal and zeros elsewhere.
N: int
Number of rows in the output.
M: int, optional
Number of columns in the output. If None, defaults to N.
K: int, optional
Python Programming by Prof.B.Sreenivasu Sreyas Institute of Engineering and Technology (Autonomous) Hyderabad Page 28 of 77
Index of the diagonal: 0 (the default) refers to the main diagonal, a positive value refers to an upper
diagonal, and a negative value to a lower diagonal.
dtype: data-type, optional
Data-type of the returned array.
Identity()
numpy.identity(n, dtype=None)
Return the identity array.
The identity array is a square array with ones on the main diagonal.
----------------------------------------------------------------------------------------------------------------------------------
Python Programming by Prof.B.Sreenivasu Sreyas Institute of Engineering and Technology (Autonomous) Hyderabad Page 29 of 77
How to read elements from Array using indexing and slicing
-----------------------------------------------------------------------------------
❑ Using index we can read only one element
❑ Slicing uses multiple indexes to read more than one value
❑ Using this approach we can read elements of any dimension
Python Programming by Prof.B.Sreenivasu Sreyas Institute of Engineering and Technology (Autonomous) Hyderabad Page 30 of 77
Slicing on matrix:
matrix[row_lower:row_upper,col_lower:col_upper]
1 2 3 4
5 6 7 8
9 10 11 12
13 14 15 16
Advanced Indexing:
Using numpy advanced indexing we can read selected values from matrix using collection of tuples
which represent row and column index. It allows to read even using condition.
Advanced indexing is classified into two categories.
▪ Integer based index
▪ Boolean based index
Integer based index:
In integer based we try to create a collection which consist of tuples, where each tuple represent
rowindex and colindex.
Python Programming by Prof.B.Sreenivasu Sreyas Institute of Engineering and Technology (Autonomous) Hyderabad Page 31 of 77
Boolean based index:
In this approach we defined boolean expression in indices.
If the expression return True, the value is return else value is not return from array.
Python Programming by Prof.B.Sreenivasu Sreyas Institute of Engineering and Technology (Autonomous) Hyderabad Page 32 of 77
Control the iteration order:
Depending on application requirement, we can access or process the element in specific order.
The nditr() function return an iterator object, which control the order of elements.
We can define the order as row major order or column major order.
Which is represented using “C” or “F”.
Python Programming by Prof.B.Sreenivasu Sreyas Institute of Engineering and Technology (Autonomous) Hyderabad Page 33 of 77
Using external loop
Array manipulations
-----------------------------
reshape:
This gives new shape to the array without modifying existing data. The shape define the number of
rows and columns.
Syntax:
np.reshape(array,newshape)
Python Programming by Prof.B.Sreenivasu Sreyas Institute of Engineering and Technology (Autonomous) Hyderabad Page 34 of 77
np.flat : one dimensional iterator over the array.
numpy.transpose()
This function/method returns transpose of matrix (OR) this method returns reverse axis of matrix.
This function receives the input as array and transpose and return modified array.
Python Programming by Prof.B.Sreenivasu Sreyas Institute of Engineering and Technology (Autonomous) Hyderabad Page 35 of 77
ndarray.T
T represents transposed array/matrix
This will return new matrix with changes.
It is member/method of ndarray.
❑ numpy.swapaxes(array,axis1,axis2)
❑ This function is used to interchange axis of an array.
Python Programming by Prof.B.Sreenivasu Sreyas Institute of Engineering and Technology (Autonomous) Hyderabad Page 36 of 77
numpy.rollaxis()
rollaxis function will roll the specified axis in backward direction until specified position.
Syntax: numpy.rollaxis(a,axis,start=0)
np.expand_dim(array,axis)
This function is used to expand or modify dimension of a specified array.
We can insert new axis by defining the position.
Python Programming by Prof.B.Sreenivasu Sreyas Institute of Engineering and Technology (Autonomous) Hyderabad Page 37 of 77
Arithmetic Operations on numpy array
------------------------------------------------------
❖ numpy provides various functions to perform arithmetic operations.
The following methods provided by ndarray.
▪ add()
▪ subtract()
▪ multiply()
▪ divide()
▪ dot()
▪ floor_divide()
▪ mod()
▪ power()
All above operations can be done using operators.
Example: add() ➔ + , subtract() ➔ -
>>> a1=np.array([1,2,3])
>>> a2=np.array([4,5,6])
>>> a3=np.add(a1,a2)
>>> print(a1,a2,a3,sep="\n")
[1 2 3]
[4 5 6]
[5 7 9]
>>> m1=np.array([[1,2,3],
... [4,5,6],
... [7,8,9]])
>>> m2=np.array([[3,4,5],
... [9,8,7],
... [3,2,1]])
>>> m3=m1+m2
>>> print(m1,m2,m3,sep="\n")
[[1 2 3]
[4 5 6]
Python Programming by Prof.B.Sreenivasu Sreyas Institute of Engineering and Technology (Autonomous) Hyderabad Page 38 of 77
[7 8 9]]
[[3 4 5]
[9 8 7]
[3 2 1]]
[[ 4 6 8]
[13 13 13]
[10 10 10]]
>>>
numpy.subtract(x1,x2)
Subtract arguments, element-wise.
>>> a=np.array([4,5,6])
>>> b=np.array([1,2,3])
>>> c=np.subtract(a,b)
>>> print(a,b,c,sep="\n")
[4 5 6]
[1 2 3]
[3 3 3]
>>> x=np.array([[4,5,6],
... [8,9,10]])
>>> y=np.array([[1,2,3],
... [4,5,6]])
>>> z=np.subtract(x,y)
>>> print(x,y,z,sep="\n")
[[ 4 5 6]
[ 8 9 10]]
[[1 2 3]
[4 5 6]]
[[3 3 3]
[4 4 4]]
numpy.multiply(x1,x2)
Multiply arguments element-wise.
>>> a=np.array([4,5,6])
Python Programming by Prof.B.Sreenivasu Sreyas Institute of Engineering and Technology (Autonomous) Hyderabad Page 39 of 77
>>> b=np.array([1,2,3])
>>> c=np.multiply(a,b)
>>> print(a,b,c,sep="\n")
[4 5 6]
[1 2 3]
[ 4 10 18]
>>> x=np.array([[4,5,6],
... [8,9,10]])
>>> y=np.array([[1,2,3],
... [4,5,6]])
>>> z=np.multiply(x,y)
>>> print(x,y,z,sep="\n")
[[ 4 5 6]
[ 8 9 10]]
[[1 2 3]
[4 5 6]]
[[ 4 10 18]
[32 45 60]]
❑ numpy.dot(a,b)
❑ Dot product of two arrays
>>> m1=np.array([[1,2],
... [3,4]])
>>> m2=np.array([[4,5],
... [6,7]])
>>> m3=np.dot(m1,m2)
>>> print(m1,m2,m3,sep="\n")
[[1 2]
[3 4]]
[[4 5]
[6 7]]
[[16 19]
[36 43]]
Python Programming by Prof.B.Sreenivasu Sreyas Institute of Engineering and Technology (Autonomous) Hyderabad Page 40 of 77
>>>
numpy.divide(x1,x2)
Divide arguments element-wise.
>>> a=np.array([4,5,6])
>>> b=np.array([1,2,3])
>>> c=np.divide(a,b)
>>> print(a,b,c,sep="\n")
[4 5 6]
[1 2 3]
[4. 2.5 2. ]
numpy.floor_divide(x1,x2)
Divide arguments element-wise. Return result in integer
>>> a=np.array([4,5,6])
>>> b=np.array([1,2,3])
>>> d=np.floor_divide(a,b)
>>> print(a,b,d,sep="\n")
[4 5 6]
[1 2 3]
[4 2 2]
>>>
numpy.mod(x1, x2)
Returns the element-wise remainder of division.
>>> a=np.array([4,5,6])
>>> b=np.array([1,2,3])
>>> c=np.mod(a,b)
>>> print(a,b,c,sep="\n")
[4 5 6]
[1 2 3]
[0 1 0]
>>>
Python Programming by Prof.B.Sreenivasu Sreyas Institute of Engineering and Technology (Autonomous) Hyderabad Page 41 of 77
numpy.power(x1,x2)
First array elements raised to powers from second array, element-wise.
>>> a=np.array([4,5,6])
>>> b=np.array([1,2,3])
>>> c=np.power(a,b)
>>> print(a,b,c,sep="\n")
[4 5 6]
[1 2 3]
[ 4 25 216]
Python Programming by Prof.B.Sreenivasu Sreyas Institute of Engineering and Technology (Autonomous) Hyderabad Page 42 of 77
Statistical Operations on numpy arrays
------------------------------------------------------
➢ Numpy library provides the functions to perform statistical operations on array.
▪ amax()
▪ amin()
▪ mean()
▪ median()
▪ var()
▪ std()
amax()
Return the maximum of an array or maximum along an axis.
numpy.amax(a, axis=None)
>>> a=np.array([10,20,30,40,50])
>>> np.amax(a)
50
>>> b=np.array([[1,2,3],
... [4,5,6],
... [7,8,9]])
>>> np.amax(b)
9
>>> np.amax(b,axis=0)
array([7, 8, 9])
>>> np.amax(b,axis=1)
array([3, 6, 9])
amin()
numpy.amin(a, axis=None)
Return the minimum of an array or minimum along an axis.
>>> a=np.array([10,20,30,40,50])
>>> np.amin(a)
10
>>> b=np.array([[1,2,3],
Python Programming by Prof.B.Sreenivasu Sreyas Institute of Engineering and Technology (Autonomous) Hyderabad Page 43 of 77
... [4,5,6],
... [7,8,9]])
>>> np.amin(b)
1
>>> np.amin(b,axis=0)
array([1, 2, 3])
>>> np.amin(b,axis=1)
array([1, 4, 7])
>>>
mean()
numpy.mean(a, axis=None)
Compute the arithmetic mean along the specified axis.
Returns the average of the array elements. The average is taken over the flattened array by default,
otherwise over the specified axis. float64 intermediate and return values are used for integer inputs.
a=np.array([1,2,3,4,5,6,7,8,9,10])
print(a)
[ 1 2 3 4 5 6 7 8 9 10]
>>> m=np.mean(a)
>>> print(m)
5.5
>>> b=np.array([[1,2,3],
... [4,5,6],
... [7,8,9]])
>>> print(b)
[[1 2 3]
[4 5 6]
[7 8 9]]
>>> m=np.mean(b)
>>> print(m)
5.0
>>> m1=np.mean(b,axis=0)
>>> print(m1)
[4. 5. 6.]
>>> m2=np.mean(b,axis=1)
Python Programming by Prof.B.Sreenivasu Sreyas Institute of Engineering and Technology (Autonomous) Hyderabad Page 44 of 77
>>> print(m2)
[2. 5. 8.]
>>>
median()
numpy.median(a, axis=None)
➢ Compute the median along the specified axis.
➢ Returns the median of the array elements.
➢ This function returns middle element
➢ Sort the elements of array in ascending order
➢ If the number of elements in array is odd number, it returns middle element
➢ If the number of elements in array is even number, it read two middle elements, add it and
divide with 2
>>> a=np.array([1,2,3,4,5,6,7])
>>> print(a)
[1 2 3 4 5 6 7]
>>> np.median(a)
4.0
>>> b=np.array([1,2,3,4,5,6,7,8])
>>> print(b)
[1 2 3 4 5 6 7 8]
>>> np.median(b)
4.5
var()
numpy.var(a, axis=None)
❑ Compute the variance along the specified axis.
❑ Returns the variance of the array elements, a measure of the spread of a distribution. The
variance is computed for the flattened array by default, otherwise over the specified axis.
❑ variance=sum(sqr(mean-xi))/total of number of elements
❑ Xi is an each element of array
>>> a=np.array([1,2,3,4,5])
>>> print(a)
[1 2 3 4 5]
Python Programming by Prof.B.Sreenivasu Sreyas Institute of Engineering and Technology (Autonomous) Hyderabad Page 45 of 77
>>> np.var(a)
2.0
std()
numpy.std(a, axis=None)
➢ Compute the standard deviation along the specified axis.
➢ Returns the standard deviation, a measure of the spread of a distribution, of the array
elements. The standard deviation is computed for the flattened array by default, otherwise
over the specified axis.
std=sqrt(var)
>>> a=np.array([1,2,3,4,5])
>>> print(a)
[1 2 3 4 5]
>>> np.var(a)
2.0
>>> np.std(a)
1.4142135623730951
>>> b=np.array([1,2,3,4,5,6,7,8,9,10])
>>> np.var(b)
8.25
>>> np.std(b)
2.8722813232690143
>>> import math
>>> math.sqrt(np.var(b))
2.8722813232690143
Sorting
The sort() function returns a sorted copy of the input array. It has the following parameters.
a:Array to be sorted
axis:The axis along which the array is to be sorted. If none, the array is flattened, sorting on the
Python Programming by Prof.B.Sreenivasu Sreyas Institute of Engineering and Technology (Autonomous) Hyderabad Page 46 of 77
last axis
kind:Default is quicksort
order: If the array contains fields, the order of fields to be sorted
numpy.argsort()
➢ The numpy.argsort() function performs an indirect sort on input array, along the given axis
and using a specified kind of sort to return the array of indices of data. This indices array is
used to construct the sorted array.
Python Programming by Prof.B.Sreenivasu Sreyas Institute of Engineering and Technology (Autonomous) Hyderabad Page 47 of 77
numpy.where()
The where() function returns the indices of elements in an input array where the given condition is
satisfied.
>>> x=np.array([10,0,0,20,30,0,0,40,0,0,50])
>>> i=np.where(x==0)
...
>>> print(i)
...
(array([1, 2, 5, 6, 8, 9], dtype=int64),)
>>> y=x[i]
...
>>> print(y)
...
[0 0 0 0 0 0]
>>> i=np.where(x>20)
...
>>> print(i)
...
(array([ 4, 7, 10], dtype=int64),)
>>> z=x[i]
...
>>> print(z)
...
Python Programming by Prof.B.Sreenivasu Sreyas Institute of Engineering and Technology (Autonomous) Hyderabad Page 48 of 77
[30 40 50]
>>>
numpy.extract()
The extract() function returns the elements satisfying any condition.
>>> y=np.extract(x==0,x)
>>> print(y)
[0 0 0 0 0 0]
>>> z=np.extract(x%2==0,x)
>>> print(z)
[10 0 0 20 30 0 0 40 0 0 50]
>>>
NumPy package contains a Matrix library numpy.matlib. This module has functions that return
matrices instead of ndarray objects.
matlib.empty()
The matlib.empty() function returns a new matrix without initializing the entries.
>>> b=matlib.empty((3,3))
>>> print(b)
[[0.00e+000 0.00e+000 0.00e+000]
[0.00e+000 0.00e+000 1.52e-321]
[0.00e+000 0.00e+000 0.00e+000]]
>>> type(b)
...
<class 'numpy.matrix'>
>>> c=matlib.empty((3,3),dtype=np.int8)
>>> print(c)
[[0 0 0]
[0 0 1]
[0 0 0]]
Python Programming by Prof.B.Sreenivasu Sreyas Institute of Engineering and Technology (Autonomous) Hyderabad Page 49 of 77
Matlib.ones()
Matlib.eye()
This function returns a matrix with 1 along the diagonal elements and the zeros elsewhere.
>>> m2=matlib.eye(4,4,1)
>>> print(m2)
[[0. 1. 0. 0.]
[0. 0. 1. 0.]
[0. 0. 0. 1.]
[0. 0. 0. 0.]]
>>> m3=matlib.eye(4,4,-1)
>>> print(m3)
[[0. 0. 0. 0.]
[1. 0. 0. 0.]
[0. 1. 0. 0.]
[0. 0. 1. 0.]]
>>> m1=matlib.eye(4)
>>> print(m1)
[[1. 0. 0. 0.]
[0. 1. 0. 0.]
[0. 0. 1. 0.]
Python Programming by Prof.B.Sreenivasu Sreyas Institute of Engineering and Technology (Autonomous) Hyderabad Page 50 of 77
[0. 0. 0. 1.]]
numpy.matlib.identity()
The numpy.matlib.identity() function returns the Identity matrix of the given size. An identity
matrix is a square matrix with all diagonal elements as 1.
>>> m1=matlib.identity(4)
>>> print(m1)
[[1. 0. 0. 0.]
[0. 1. 0. 0.]
[0. 0. 1. 0.]
[0. 0. 0. 1.]]
>>>
numpy.stack(arrays, axis=0,)
➢ Join a sequence of arrays along a new axis.
>>> a=np.array([1,2,3],dtype=np.int8)
>>> b=np.array([4,5,6],dtype=np.int8)
>>> print(a)
[1 2 3]
>>> print(b)
[4 5 6]
>>> np.stack((a,b))
array([[1, 2, 3],
[4, 5, 6]], dtype=int8)
numpy.vstack(tupe)
Stack arrays in sequence vertically (row wise).
>>> a=np.array([[1],[2],[3]])
>>> print(a)
[[1]
[2]
Python Programming by Prof.B.Sreenivasu Sreyas Institute of Engineering and Technology (Autonomous) Hyderabad Page 51 of 77
[3]]
>>> b=np.array([[4],[5],[6]])
>>> print(b)
[[4]
[5]
[6]]
>>> c=np.vstack((a,b))
>>> print(c)
[[1]
[2]
[3]
[4]
[5]
[6]]
numpy.hstack()
Stack arrays in sequence horizontally (column wise).
>>> a=np.array([1,2,3])
>>> b=np.array([4,5,6])
>>> c=np.hstack((a,b))
>>> print(a)
[1 2 3]
>>> print(b)
[4 5 6]
>>> print(c)
[1 2 3 4 5 6]
>>> a=np.array([1,2,3,4,5,6,7,8,9,10])
>>> b=np.split(a,(3,6))
>>> print(a)
[ 1 2 3 4 5 6 7 8 9 10]
>>> print(b)
Python Programming by Prof.B.Sreenivasu Sreyas Institute of Engineering and Technology (Autonomous) Hyderabad Page 52 of 77
[array([1, 2, 3]), array([4, 5, 6]), array([ 7, 8, 9, 10])]
>>>
>>> a=np.array([1,2,3])
>>> b=np.array([4,5,6])
>>> c=np.concatenate((a,b))
>>> print(c)
[1 2 3 4 5 6]
a=np.array([[1],[2],[3]])
b=np.array([[4],[5],[6]])
c=np.concatenate((a,b),axis=0)
>>> print(a)
[[1]
[2]
[3]]
>>> print(b)
[[4]
[5]
[6]]
>>> print(c)
[[1]
[2]
[3]
[4]
[5]
[6]]
>>> d=np.concatenate((a,b),axis=1)
>>> print(d)
[[1 4]
[2 5]
[3 6]]
Python Programming by Prof.B.Sreenivasu Sreyas Institute of Engineering and Technology (Autonomous) Hyderabad Page 53 of 77
>>>
>>> print(dot_product)
(17+44j)
>>> mat1=np.array([[1,2],[3,4]])
>>> mat2=np.array([[4,5],[2,3]])
>>> mat3=np.dot(mat1,mat2)
>>> print(mat1)
[[1 2]
[3 4]]
>>> print(mat2)
[[4 5]
[2 3]]
>>> print(mat3)
[[ 8 11]
[20 27]]
>>>
numpy.matmul(x1, x2)
Python Programming by Prof.B.Sreenivasu Sreyas Institute of Engineering and Technology (Autonomous) Hyderabad Page 54 of 77
Matrix product of two arrays.
>>> mat1=np.array([[1,2],[3,4]])
>>> mat2=np.array([[4,5],[2,3]])
>>> mat3=np.matmul(mat1,mat2)
>>> print(mat1)
[[1 2]
[3 4]]
>>> print(mat2)
[[4 5]
[2 3]]
>>> print(mat3)
[[ 8 11]
[20 27]]
linalg.solve(a, b)
➢ Solve a linear matrix equation, or system of linear scalar equations.
Parameters:
a(…, M, M) array_like
Coefficient matrix.
b{(…, M,), (…, M, K)}, array_like
Ordinate or “dependent variable” values.
x + 2y = 4
3x − 5y = 1
Python Programming by Prof.B.Sreenivasu Sreyas Institute of Engineering and Technology (Autonomous) Hyderabad Page 55 of 77
Example programs:
import numpy as py
# display the system of linear equations
print("the system of equations are:")
print('x + 2y = 4')
print ('AND')
print('3x − 5y = 1')
# form the matrices from the equations
A = py.array ([[1,2],[3,-5]])
B=py.array([4,1])
#function call nd result calculation
C=py.linalg.solve(A,B)
# display the result
print("The solution to the linear equation using matrix method is :")
print("[x,y]=",C)
Output:
the system of equations are:
x + 2y = 4
AND
3x − 5y = 1
The solution to the linear equation using matrix method is :
[x,y]= [2. 1.]
>>>
numpy.save
numpy.save(file, arr)
Save an array to a binary file in NumPy .npy format.
Example:
import numpy as np
a=np.array([10,20,30,40,50])
print(a)
f=open("e:\\file1.npy","wb")
np.save(f,a)
Python Programming by Prof.B.Sreenivasu Sreyas Institute of Engineering and Technology (Autonomous) Hyderabad Page 56 of 77
f.close()
savetxt()
numpy.savetxt(fname, X)
Save an array to a text file.
import numpy as np
a=np.array([10,20,30,40,50])
f=open("e:\\file4.txt","w")
np.savetxt(f,a)
f.close()
----------------------------------------------------------------------------------------------------------------------------------
Python Programming by Prof.B.Sreenivasu Sreyas Institute of Engineering and Technology (Autonomous) Hyderabad Page 57 of 77
----------------------------------------------------------------------------------------------------------------------------------
Hackerrank coding challenges on ‘Numpy’
a = numpy.array([1,2,3,4,5])
print a[1] #2
b = numpy.array([1,2,3,4,5],float)
print b[1] #2.0
In the above example, numpy.array() is used to convert a list into a NumPy array. The second
argument (float) can be used to set the type of array elements.
----------------------------------------------------------------------------------------------------------------------------------
Task -1
You are given a space separated list of numbers.
Your task is to print a reversed NumPy array with the element type float.
Input Format
A single line of input containing space separated numbers.
Output Format
Print the reverse NumPy array with type float.
Sample Input
1 2 3 4 -8 -10
Sample Output
[-10. -8. 4. 3. 2. 1.]
Python Programming by Prof.B.Sreenivasu Sreyas Institute of Engineering and Technology (Autonomous) Hyderabad Page 58 of 77
import numpy
def arrays(arr):
# complete this function
# use numpy.array
array1=numpy.array(arr[::-1],dtype=numpy.float64)
return array1
---------------------------------------------------------------------------------------------------------------
shape
The shape tool gives a tuple of array dimensions and can be used to change the dimensions of an
array.
(a). Using shape to get array dimensions
import numpy
change_array = numpy.array([1,2,3,4,5,6])
change_array.shape = (3, 2)
print change_array
#Output
[[1 2]
[3 4]
[5 6]]
Python Programming by Prof.B.Sreenivasu Sreyas Institute of Engineering and Technology (Autonomous) Hyderabad Page 59 of 77
reshape
The reshape tool gives a new shape to an array without changing its data. It creates a new array and
does not modify the original array itself.
import numpy
my_array = numpy.array([1,2,3,4,5,6])
print numpy.reshape(my_array,(3,2))
#Output
[[1 2]
[3 4]
[5 6]]
Task -2
You are given a space separated list of nine integers. Your task is to convert this list into
a X NumPy array.
Input Format
A single line of input containing space separated integers.
Output Format
Print the X NumPy array.
Sample Input
123456789
Sample Output
[[1 2 3]
[4 5 6]
[7 8 9]]
--------------------------------------------------
import numpy
list1=input().split()
array1=numpy.array(list1,dtype=numpy.int64)
array2=numpy.reshape(array1,(3,3))
print(array2)
----------------------------------------------------------------------------------------------------------------
Python Programming by Prof.B.Sreenivasu Sreyas Institute of Engineering and Technology (Autonomous) Hyderabad Page 60 of 77
Transpose
We can generate the transposition of an array using the tool numpy.transpose.
It will not affect the original array, but it will create a new array.
import numpy
my_array = numpy.array([[1,2,3],
[4,5,6]])
print numpy.transpose(my_array)
#Output
[[1 4]
[2 5]
[3 6]]
Flatten
The tool flatten creates a copy of the input array flattened to one dimension.
import numpy
my_array = numpy.array([[1,2,3],
[4,5,6]])
print my_array.flatten()
#Output
[1 2 3 4 5 6]
Task-3
You are given a NXM integer array matrix with space separated elements ( N= rows and M =
columns).
Your task is to print the transpose and flatten results.
Input Format
The first line contains the space separated values of N and M .
The next lines contains the space separated elements of M columns.
Output Format
First, print the transpose array and then print the flatten.
Sample Input
Python Programming by Prof.B.Sreenivasu Sreyas Institute of Engineering and Technology (Autonomous) Hyderabad Page 61 of 77
22
12
34
Sample Output
[[1 3]
[2 4]]
[1 2 3 4]
import numpy
N,M=map(int,input().split())
list1=[]
for i in range(N):
row=list(map(int,input().split()))
list1.append(row)
array2=numpy.array(list1)
array3=numpy.transpose(array2)
print(array3)
print(array2.flatten())
----------------------------------------------------------------------------------------------------------------
Concatenate
Two or more arrays can be concatenated together using the concatenate function with a tuple of the
arrays to be joined:
import numpy
array_1 = numpy.array([1,2,3])
array_2 = numpy.array([4,5,6])
array_3 = numpy.array([7,8,9])
#Output
[1 2 3 4 5 6 7 8 9]
Python Programming by Prof.B.Sreenivasu Sreyas Institute of Engineering and Technology (Autonomous) Hyderabad Page 62 of 77
If an array has more than one dimension, it is possible to specify the axis along which multiple
arrays are concatenated. By default, it is along the first dimension.
import numpy
array_1 = numpy.array([[1,2,3],[0,0,0]])
array_2 = numpy.array([[0,0,0],[7,8,9]])
#Output
[[1 2 3 0 0 0]
[0 0 0 7 8 9]]
Task-4
You are given two integer arrays of size N X P and M X P (N & M are rows, and P is the column).
Your task is to concatenate the arrays along axis 0 .
Input Format
The first line contains space separated integers N , M and P .
The next N lines contains the space separated elements of the P columns.
After that, the next M lines contains the space separated elements of the P columns.
Output Format
Print the concatenated array of size(N+M)xP.
Sample Input
432
12
12
12
12
34
34
34
Sample Output
[[1 2]
[1 2]
[1 2]
[1 2]
Python Programming by Prof.B.Sreenivasu Sreyas Institute of Engineering and Technology (Autonomous) Hyderabad Page 63 of 77
[3 4]
[3 4]
[3 4]]
----------------------
import numpy
N,M,P=map(int,input().split())
list1=[]
list2=[]
for i in range(N):
row_n=list(map(int,input().split()))
list1.append(row_n)
for i in range(M):
row_m=list(map(int,input().split()))
list2.append(row_m)
array1=numpy.array(list1)
array2=numpy.array(list2)
array3=numpy.concatenate((array1,array2),axis=0)
print(array3)
----------------------------------------------------------------------------------------------------------------------------------
-------------------------
zeros
The zeros tool returns a new array with a given shape and type filled with 's.
import numpy
Task-5
You are given the shape of the array in the form of space-separated integers, each integer
representing the size of different dimensions, your task is to print an array of the given shape
and integer type using the tools numpy.zeros and numpy.ones.
Input Format
A single line containing the space-separated integers.
Constraints
Output Format
First, print the array using the numpy.zeros tool and then print the array with the numpy.ones tool.
Sample Input 0
333
Sample Output 0
[[[0 0 0]
[0 0 0]
[0 0 0]]
[[0 0 0]
[0 0 0]
[0 0 0]]
[[0 0 0]
[0 0 0]
[0 0 0]]]
[[[1 1 1]
[1 1 1]
[1 1 1]]
[[1 1 1]
[1 1 1]
[1 1 1]]
[[1 1 1]
Python Programming by Prof.B.Sreenivasu Sreyas Institute of Engineering and Technology (Autonomous) Hyderabad Page 65 of 77
[1 1 1]
[1 1 1]]]
Explanation 0
Print the array built using numpy.zeros and numpy.ones tools and you get the result as shown.
import numpy
n=tuple(map(int,input().split()))
print(numpy.zeros(n, dtype=numpy.int64))
print(numpy.ones(n, dtype=numpy.int64))
----------------------------------------------------------------------------------------------------------------------------------
-------------------------
identity
The identity tool returns an identity array. An identity array is a square matrix with all the main
diagonal elements as 1 and the rest as 0 . The default type of elements is float.
import numpy
print numpy.identity(3) #3 is for dimension 3 X 3
#Output
[[ 1. 0. 0.]
[ 0. 1. 0.]
[ 0. 0. 1.]]
eye
The eye tool returns a 2-D array with 's as the diagonal and 's elsewhere. The diagonal can be main,
upper or lower depending on the optional parameter . A positive is for the upper diagonal, a
negative is for the lower, and a (default) is for the main diagonal.
import numpy
print numpy.eye(8, 7, k = 1) # 8 X 7 Dimensional array with first upper diagonal 1.
#Output
[[ 0. 1. 0. 0. 0. 0. 0.]
[ 0. 0. 1. 0. 0. 0. 0.]
[ 0. 0. 0. 1. 0. 0. 0.]
[ 0. 0. 0. 0. 1. 0. 0.]
[ 0. 0. 0. 0. 0. 1. 0.]
Python Programming by Prof.B.Sreenivasu Sreyas Institute of Engineering and Technology (Autonomous) Hyderabad Page 66 of 77
[ 0. 0. 0. 0. 0. 0. 1.]
[ 0. 0. 0. 0. 0. 0. 0.]
[ 0. 0. 0. 0. 0. 0. 0.]]
Task-6
Your task is to print an array of size X with its main diagonal elements as 's and 's everywhere
else.
Note
In order to get alignment correct, please insert the line below the numpy import.
Input Format
A single line containing the space separated values of and .
denotes the rows.
denotes the columns.
Output Format
Print the desired X array.
Sample Input
33
Sample Output
[[ 1. 0. 0.]
[ 0. 1. 0.]
[ 0. 0. 1.]]
------------------
import numpy
numpy.set_printoptions(legacy='1.13')
n,m=map(int,input().split())
print(numpy.eye(n,m,k=0))
----------------------------------------------------------------------------------------------------------------
Basic mathematical functions operate element-wise on arrays. They are available both as operator
overloads and as functions in the NumPy module.
import numpy
a = numpy.array([1,2,3,4], float)
b = numpy.array([5,6,7,8], float)
Python Programming by Prof.B.Sreenivasu Sreyas Institute of Engineering and Technology (Autonomous) Hyderabad Page 67 of 77
print a + b #[ 6. 8. 10. 12.]
print numpy.add(a, b) #[ 6. 8. 10. 12.]
print a % b #[ 1. 2. 3. 4.]
print numpy.mod(a, b) #[ 1. 2. 3. 4.]
Task-7
You are given two integer arrays, and of dimensions X.
Your task is to perform the following operations:
1. Add ( + )
2. Subtract ( - )
3. Multiply ( * )
4. Integer Division ( / )
5. Mod ( % )
6. Power ( ** )
Note
There is a method numpy.floor_divide() that works like numpy.divide() except it performs a floor
division.
Input Format
The first line contains two space separated integers, and .
The next lines contains space separated integers of array .
The following lines contains space separated integers of array .
Python Programming by Prof.B.Sreenivasu Sreyas Institute of Engineering and Technology (Autonomous) Hyderabad Page 68 of 77
Output Format
Print the result of each operation in the given order under Task.
Sample Input
14
1234
5678
Sample Output
[[ 6 8 10 12]]
[[-4 -4 -4 -4]]
[[ 5 12 21 32]]
[[0 0 0 0]]
[[1 2 3 4]]
[[ 1 64 2187 65536]]
Use // for division in Python 3.
-----------------
import numpy
n,m=map(int,input().split())
list1=[]
list2=[]
for i in range(n):
row1=list(map(int,input().split()))
list1.append(row1)
for i in range(n):
row2=list(map(int,input().split()))
list2.append(row2)
arrayA=numpy.array(list1)
arrayB=numpy.array(list2)
print(numpy.add(arrayA,arrayB))
print(numpy.subtract(arrayA,arrayB))
print(numpy.multiply(arrayA,arrayB))
print(numpy.floor_divide(arrayA,arrayB))
print(numpy.mod(arrayA,arrayB))
print(numpy.power(arrayA,arrayB))
----------------------------------------------------------------------------------------------------------------
Python Programming by Prof.B.Sreenivasu Sreyas Institute of Engineering and Technology (Autonomous) Hyderabad Page 69 of 77
sum
The sum tool returns the sum of array elements over a given axis.
import numpy
Task -8
You are given a 2-D array with dimensions X.
Your task is to perform the tool over axis and then find the of that result.
Input Format
The first line of input contains space separated values of and .
The next lines contains space separated integers.
Output Format
Compute the sum along axis . Then, print the product of that sum.
Sample Input
22
12
Python Programming by Prof.B.Sreenivasu Sreyas Institute of Engineering and Technology (Autonomous) Hyderabad Page 70 of 77
34
Sample Output
24
Explanation
The sum along axis = [ ]
The product of this sum =
----------------------------------------------------------------------------------------------------------------------------------
import numpy
n,m=map(int,input().split())
list1=[]
for i in range(n):
row=list(map(int,input().split()))
list1.append(row)
array1=numpy.array(list1)
sum1=numpy.sum(array1,axis=0)
print(numpy.prod(sum1))
----------------------------------------------------------------------------------------------------------------------------------
min
The tool min returns the minimum value along a given axis.
import numpy
Task-9
You are given a 2-D array with dimensions X.
Your task is to perform the min function over axis and then find the max of that.
Input Format
The first line of input contains the space separated values of and .
The next lines contains space separated integers.
Output Format
Compute the min along axis and then print the max of that result.
Sample Input
42
25
37
13
40
Sample Output
3
Explanation
The min along axis =
The max of =
----------------------------------------------------------------------------------------------------------------------------------
import numpy
Python Programming by Prof.B.Sreenivasu Sreyas Institute of Engineering and Technology (Autonomous) Hyderabad Page 72 of 77
n,m=map(int,input().split())
list1=[]
for i in range(n):
row=list(map(int,input().split()))
list1.append(row)
array1=numpy.array(list1)
min_array1=numpy.min(array1,axis=1)
print(numpy.max(min_array1))
======================================================================================
mean
The mean tool computes the arithmetic mean along the specified axis.
import numpy
A = numpy.array([ 1, 2 ])
B = numpy.array([ 3, 4 ])
A = numpy.array([ 1, 2 ])
B = numpy.array([ 3, 4 ])
Task-11
You are given two arrays A and B. Both have dimensions of NXN.
Your task is to compute their matrix product.
Input Format
The first line contains the integer N .
The next N lines contains N space separated integers of array A .
The following N lines contains N space separated integers of array B .
Output Format
Print the matrix multiplication of A and B .
Sample Input
2
12
34
12
34
Sample Output
Python Programming by Prof.B.Sreenivasu Sreyas Institute of Engineering and Technology (Autonomous) Hyderabad Page 75 of 77
[[ 7 10]
[15 22]]
======================================================================================
import numpy
N=int(input())
A=[]
for i in range(N):
row=list(map(int,input().split()))
A.append(row)
B=[]
for i in range(N):
row=row=list(map(int,input().split()))
B.append(row)
arrayA=numpy.array(A)
arrayB=numpy.array(B)
res=numpy.dot(arrayA,arrayB)
print(res)
======================================================================================
inner
The inner tool returns the inner product of two arrays.
import numpy
A = numpy.array([0, 1])
B = numpy.array([3, 4])
A = numpy.array([0, 1])
B = numpy.array([3, 4])
Task-12
You are given two arrays: A and B .
Your task is to compute their inner and outer product.
Input Format
The first line contains the space separated elements of array A .
The second line contains the space separated elements of array B.
Output Format
First, print the inner product.
Second, print the outer product.
Sample Input
01
23
Sample Output
3
[[0 0]
[2 3]]
======================================================================================
import numpy
A=numpy.array(list(map(int,input().split())))
B=numpy.array(list(map(int,input().split())))
print(numpy.inner(A,B))
print(numpy.outer(A,B))
======================================================================================
Python Programming by Prof.B.Sreenivasu Sreyas Institute of Engineering and Technology (Autonomous) Hyderabad Page 77 of 77