Download as ppt, pdf, or txt
Download as ppt, pdf, or txt
You are on page 1of 46

Numpy-Array

• Numpy is the core library for scientific computing in Python. It


provides a high-performance multidimensional array object, and tools
for working with these arrays
• NumPy’s main object is the homogeneous multidimensional array. It
is a table of elements (usually numbers), all of the same type, indexed
by a tuple of positive integers. In NumPy dimensions are called axes.
• EG:[[ 1., 0., 0.],
• [ 0., 1., 2.]]
How to use numpy for creating arrays
• NumPy’s array class is called ndarray. It is also known by the alias
array. The more important attributes of an ndarray object are:
• ndarray.ndim-the number of axes (dimensions) of the array.
• ndarray.shape-the dimensions of the array. This is a tuple of integers
indicating the size of the array in each dimension. For a matrix with n
rows and m columns, shape will be (n,m). The length of the shape
tuple is therefore the number of axes, ndim.
How to use numpy for creating arrays
• ndarray.size-the total number of elements of the array. This is equal
to the product of the elements of shape.
• ndarray.dtype-an object describing the type of the elements in the
array. One can create or specify dtype’s using standard Python types.
Additionally NumPy provides types of its own. numpy.int, and
numpy.float are some examples.
How to use numpy for creating arrays
• ndarray.data-the buffer containing the actual elements of the array.
Normally, we won’t need to use this attribute because we will access
the elements in an array using indexing facilities.
Various array function example
• numpy.arange. This function returns an ndarray object containing evenly spaced
values within a given range.
• import numpy as np
• a = np.arange(6)
• b= np.arange(15).reshape(3,5)
• print(a)
• print(b)

• Output-array([[ 0, 1, 2, 3, 4],
• [ 5, 6, 7, 8, 9],
• [10, 11, 12, 13, 14]])
• a.shape
• (3, 5)
Various array function example
• a.shape-Tuple of array dimensions.
• The shape property is usually used
• to get the current shape of an array, 
• Example>>> a.shape
output=(3, 5)
• a.ndim-This function is used to display the dimensions of an array
• Example
• >>> a.ndim
• output=2
Various array function example
• a.dtype-describes how the bytes in the fixed-size block of memory corresponding
to an array item should be interpreted. It describes the following aspects of the
data:
• Type of the data (integer, float, Python object, etc.)
• Example
• a=np.array([2.6, 3, 4])
• >>> a.dtype
• Output-dtype('int')
• >>> b = np.array([1.2, 3.5, 5.1])
• >>> b.dtype
• Output-dtype('float')
Various array function example
• a.size-this function returns the count of total numbers of eleme
array
Example a = np.arange(15).reshape(3, 5)
print(a.size)
• output-15
• Type()-this function returns the class to which the numpy array
• Example
• >>> type(a)
• <class 'numpy.ndarray'>
• >>> b = np.array([6, 7, 8])
• >>> b
Various array function example
• The function zeros creates an array full of zeros,, and
• np.zeros( (3,4) )
Output-array([[ 0., 0., 0., 0.],
• [ 0., 0., 0., 0.],
• [ 0., 0., 0., 0.]])
Various array function example
• the function empty creates an array whose initial content is random and depends
on the state of the memory. By default, the dtype of the created array is float
• >>> np.empty( (2,3) ) # uninitialized, output may vary
• array([[ 3.73603959e-262, 6.02658058e-154, 6.55490914e-260],
• [ 5.30498948e-313, 3.14673309e-307, 1.00000000e+000]])
Various array function example
• f = np.eye(4)-This function creates n array where all elements are
equal to zero, except for the k-th diagonal, whose values are equal to
one.
• print(f)-output- array([[1., 0., 0., 0.],
• [0., 1., 0., 0.],
• [0., 0., 1., 0.],
• [0., 0., 0., 1.]])
Various array function example
• g = np.full((4,4),6)- This function creates n array where all ele
are identicals
• Output- array([[6, 6, 6, 6],
• [6, 6, 6, 6],
• [6, 6, 6, 6],
• [6, 6, 6, 6]])
Array Creation
• import numpy as np
• a = np.array([2,3,4])
• print(a)

a = np.array(1,2,3,4) # WRONG
• print(a)
• a = np.array([1,2,3,4]) # RIGHT
• print(a)
• b = np.array([(1.5,2,3), (4,5,6)])
print( b)
• Output-array([[ 1.5, 2. , 3. ],
• [ 4. , 5. , 6. ]])
• c = np.array( [ [1,2], [3,4] ], dtype=complex )
• c
• Output-array([[ 1.+0.j, 2.+0.j],
• [ 3.+0.j, 4.+0.j]])
Array Creation

• >>> np.arange( 10, 30, 5 )


• array([10, 15, 20, 25])
• >>> np.arange( 0, 2, 0.3 ) # it accepts float arg
• array([ 0. , 0.3, 0.6, 0.9, 1.2, 1.5, 1.8])
Array Creation

• >>> np.linspace( 0, 2, 9 ) # 9 numbers from 0 to 2


• array([ 0. , 0.25, 0.5 , 0.75, 1. , 1.25, 1.5 , 1.75, 2. ])
• >>> a = np.arange(6) # 1d array
• >>> print(a)
• [0 1 2 3 4 5]
• >>> b = np.arange(12).reshape(4,3) # 2d array
• >>> print(b)
• [[ 0 1 2]
• [ 3 4 5]
• [ 6 7 8]
• [ 9 10 11]]
3D Array Creation
• c = np.arange(24).reshape(2,3,4) # 3d array
• print(c)
• [[[ 0 1 2 3]
• [ 4 5 6 7]
• [ 8 9 10 11]]
• [[12 13 14 15]
• [16 17 18 19]
• [20 21 22 23]]]
Basic Operations

• Arithmetic operators on arrays apply elementwise. A new array is


created and filled with the result.
• >>> a = np.array( [20,30,40,50] )
• >>> b = np.array([12,23,34,45])
• >>> b
• >>> c = a-b
• >>> c
Basic Operations

• b = np.array([12,23,34,45])
>>> b**2
• a = np.array( [20,30,40,50] )
>>> a<35
• Output-array([ True, True, False, False])
Matrix operations
A = np.array( [[1,1],[0,1]] )
B = np.array( [[2,0],[3,4]] )
A *( B ) # elementwise product
•OUTPUT-array([[2, 0],
• [0, 4]])
Matrix operations
A *( B ) # elementwise product
A@B # matrix product
•array([[5, 4],
• [3, 4]])
A.dot(B) # another matrix product
•array([[5, 4],
• [3, 4]])
Matrix operations
• >>> a = np.arange(10)
• >>>print( a)
• >>>print( a.sum())

• >>>print( a.min())

• >>> print(a.max())
Other Operations
• >>> b = np.arange(12).reshape(3,4)
• >>> b
• Output-array([[ 0, 1, 2, 3],
• [ 4, 5, 6, 7],
• [ 8, 9, 10, 11]])
>>> b.sum(axis=0) # sum of each column
Output-array([12, 15, 18, 21])
>>> b.min(axis=1) # min of each row
array([0, 4, 8])
Other Operations
• b = np.arange(12).reshape(3,4)
• print(b)
array([[ 0, 1, 2, 3],
• [ 4, 5, 6, 7],
• [ 8, 9, 10, 11]])

>>> b.cumsum(axis=1) # cumulative sum along each row


• Output- array([[ 0, 1, 3, 6],
• [ 4, 9, 15, 22],
• [ 8, 17, 27, 38]])
Universal Functions

• >>> B = np.arange(3)
• >>> B
• Output-array([0, 1, 2])
• >>> np.exp(B)
• Output-array([ 1. , 2.71828183, 7.3890561 ])
• >>> np.sqrt(B)
• array([ 0. , 1. , 1.41421356])
• >>> C = np.array([2., -1., 4.])
• >>> np.add(B, C)
• array([ 2., 0., 6.])
Indexing, Slicing and Iterating
• One-dimensional arrays can be indexed, sliced and iterated over, much
like lists and other Python sequences.
• >>> a = np.arange(10)**3
• >>>print( a)
• array([ 0, 1, 8, 27, 64, 125, 216, 343, 512, 729])
• >>> a[2]
•8
• >>> a[2:5]
• array([ 8, 27, 64])
Indexing, Slicing and Iterating

array([ 0, 1, 8, 27, 64, 125, 216, 343, 512, 729])


>>> a[:6:2] = -1000
print(a) # equivalent to a[0:6:2] = -1000; from start to position 6,
exclusive, set every 2nd element to -1000
•>>> a
•array([-1000, 1, -1000, 27, -1000, 125, 216, 343, 512, 729])
•>>> print(a[ : :-1] ) # reversed a
•array([ 729, 512, 343, 216, 125, -1000, 27, -1000, 1, -1000])
Indexing, Slicing and Iterating in
multidimensional
• b=np.array([[ 0, 1, 2, 3],
• [10, 11, 12, 13],
• [20, 21, 22, 23],
• [30, 31, 32, 33],
• [40, 41, 42, 43]])
• >>> b[2,3]
• 23
Indexing, Slicing and Iterating in
multidimensional
• b=np.array([[ 0, 1, 2, 3],
• [10, 11, 12, 13],
• [20, 21, 22, 23],
• [30, 31, 32, 33],
• [40, 41, 42, 43]])
print b[0:5, 1] # each column in the second column of barray
• ([ 1, 11, 21, 31, 41])
• print b[ : ,1] # equivalent to the previous example
• array([ 1, 11, 21, 31, 41])
• print b[1:3,:] # each row in the second and third row of b
• array([[10, 11, 12, 13],
• [20, 21, 22, 23]])
Indexing, Slicing and Iterating in
multidimensional
• >>> c = np.array( [[[ 0, 1, 2], # a 3D array (two stacked 2D arrays)
• ... [ 10, 12, 13]],
• ... [[100,101,102],
• ... [110,112,113]]])
• >>> c.shape
• (2, 2, 3)
Array with for loop
• import numpy as np
• a=np.array([12,21,30])
• for i in a:
print(" the elements are….." ,i)
1D array with for loop
• import numpy as np
• a=np.array([12,23,33])
• s=0
• for i in a:
• s=s+i
print("Sum of ca marks are:" ,s)
• Avg=s/3
• print(“Average of ca marks are:" ,Avg)
Array with for loop
• import numpy as np
• a=np.arange(11)
for i in a:
• if (i%2==0):
• print(“even no are….”,i)
• else:
• print(“ odd are……”,i)
Array with for loop
import numpy as np
•a=np.array([1,2,3,4,5,6,7,8,9,10])
•even=0
•odd=0
for i in a:
• if (i%2==0):
• even=even+1
• else:
• odd=odd+1
•Print(“total even are”,even)
•Print(“total odd are”,odd)
2D array with for loop
• a=np.array(([1,2,3],[4,5,6]))

• for i in range(0,2):
• for j in range(0,3):
• if (a[i][j]%2==0):
• print(”Even numbers are…." ,a[i][j])
2D array with for loop
• a=np.array(([1,2,3],[4,5,6]))
• s=0
• for i in range(0,2):
• for j in range(0,3):
• s=s+a[i][j]

• print("Sum of all the elements are:" ,s)
from numpy import *

• from numpy import *


• x = range(16)
• x = reshape(x,(4,4))
• print(x)
ARRAY CREATION AT
RUNTIME
• import numpy as np
• L=[]
• for i in range(4):
• L.append(int(input(“enter the number”)))

• a=np.array(L)
• a.shape=(2,2)
• print(a)


from numpy import *
from numpy import *
• from numpy import *
• a= array([10,20,30.5,-40])
• print("1",a)
• print("2",a+5)
• print("3",a-5)
• print("4",a*5)
• print("5",a/5)
• print("6",a%5)
• print("7",(a+5)**2-10)
• print("8",sin(a))
from numpy import *
• from numpy import *
• a=array([1,2,3,0])
• b=array([0,2,3,1])
• c=a==b
• print(“VALUE OF C1…..”,c)
• c=a>b
• print(“VALUE OF C2…..”, c)
• c=a<=b
• print(“VALUE OF C3…..”, c)
c=a>b
• print(“VALUE OF C4…..”, any(c))
from numpy import *

• from numpy import *


• a=arange(1,6)
• b=a.copy() #copying: create a seperate copy of a and call it 'b':
• print(a) op-[1 2 3 4 5]#original array
• print(b) op-[1 2 3 4 5]#copy of orginal
• b[0]=99 #change done in copy
• print(a) op-[1 2 3 4 5] #no chnge in original array
• print(b) op-[99 2 3 4 5]#change in copy
#viewing

• from numpy import *


• a=arange(1,6)
• b=a.view() #viewing: create a view of a and call it 'b':
• shadow copying
• print(a)-[1 2 3 4 5]
• print(b)-[1 2 3 4 5]
• b[0]=99
• print(a)-[99 2 3 4 5]
• print(b)-[99 2 3 4 5]
aliasing:
• from numpy import *
• a=arange(1,6)
• b=a #aliasing: give another name 'b' to array a, not copying
• print(a)-[1 2 3 4 5]
• print(b)-[1 2 3 4 5]
• b[0]=99
• print(a)-[99 2 3 4 5]
• print(b)-[99 2 3 4 5]
arange
• from numpy import *
• a=arange(10,16)
• print(a)
• b=a[1:6:2]
• print(“VALUE OF B IS….”,b)
• b=a[::]
• print(“VALUE OF B IS…..”,b)
• b=a[-2:2:-1]
• print(“b)
• b=a[:-2:]
• print(b)
from numpy import *
• from numpy import *
• a=matrix('1 2 3;4 5 6;7 8 9')
• print(a)
• b=diagonal(a)
• print(b)
m = a.max()
• print(“max value is…..”,m)
• s = a.min()
• print(“min value is ….”,s)
• sum = a.sum()
• print(“sum of value is…”,sum)ss
• m1 = a.mean()
• print(“mean is….”,m1)
• p1 = a.prod(0)
• print(“product column wise…..”,p1)
• p2 = a.prod(1)
• print(“product rowwise…..”,p2)
• //TRANSPOSE OF MATRIX
• a = np.array([[1, 2, 3], [3, 4, 5], [9, 6, 0]])

• print ("\nOriginal array:\n", a)
• print ("Transpose of array:\n", a.T)
sortk
• from numpy import *
• a=matrix([[1,2,6],[4,1,6]])
• print(a)
• b=sort(a) # sort row wise
• print(b)

• b=sort(a,axis=0) #sort column wise


• print(b)

You might also like