In [177]:
# importing required packages
import numpy as np
In [178]:
# forming numpy array
array1 = np.array([1,2,3,4])
array1
Out[178]:
In [179]:
# checking type of above formed array
print type(array1)
# checking type of element in the array
print array1.dtype
In [180]:
# Specifying the type of elements in np.array
array2 = np.array([4,3,2,7],float)
array2
Out[180]:
In [181]:
# Indexing numpy array
print array1[1]
print array2[1:]
print array1[:2]
In [182]:
# While indexing if x:y is used then we must note that x is inclusive and y is exclusive
array1[1:3]
Out[182]:
In [183]:
# Negative values in indexing are also allowed
print array1
array1[-2,]
# This returns second element from the end
Out[183]:
In [184]:
# Multidimensional array
array3 = np.array([[1,5,6],[7,8,9]])
array3
Out[184]:
In [185]:
# Indexing multidimensional array
print array3[1,]
print array3[-1,]
print array3[:,-1]
In [186]:
# Indexing multidimensional array
print array3[0:2,1:2]
print array3[:,1]
In [187]:
# Determing the dimensions of the array using shape which returns number of rows and columns in the array
array3.shape
Out[187]:
In [188]:
# len function returns the length of first axis
len(array3)
Out[188]:
In [189]:
array4 = np.array(range(12))
array4
Out[189]:
In [190]:
# Changing dimensions of the array
print array4.shape
print 'After changing the dimensions : '
array4 = array4.reshape(4,3)
print array4
In [191]:
# Checking Membership in array using 'in'. Returns a boolean value according to presence or absence of element
print 4 in array4
print 12 in array4
In [192]:
# Copying array elements from one array to another
x = np.array([2,3,4,7,8,9,10,23])
print x
y = x
print y
# Changing one of the element in original array affects the new array also.
print '\nAfter modifying original array'
x[5] = 89
print x
print y
In [193]:
# copy() function to create a seperate array array in memory
z = x.copy()
print z
# changing element in original array will not affect the new array
print '\nAfter modifying original array'
x[1] = 5
print x
print z
In [194]:
# Forming string from array elements using tostring() function
string = np.array([1,2,3],float).tostring()
string
Out[194]:
In [195]:
# Getting array elements back from string format using fromstring()
np.fromstring(string)
Out[195]:
In [196]:
# Filling an array with a scalar value using fill() function
print z
print '\nElements in the array after using fill() function'
z.fill(2)
print z
In [197]:
# Transposing multi-dimensional array using transpose() function
print array3
print '\After transposing the array'
print array3.transpose()
In [198]:
# Transforming multi-dimensional array into one dimensional using flatten() function
print array3
print '\nAfter using flatten() function'
print array3.flatten()
In [199]:
# One dimensional arrays can be merged using the function conctenate()
a = np.array([5,6,7])
b = np.array([78,99,100,12])
np.concatenate((a,b))
Out[199]:
In [200]:
# Multi-dimensional arrays can also be merged using concatenate() and mentioning axis. By default it considers first dimension.
a = np.array([[10,11],[34,22]])
b = np.array([[12,13],[15,16]])
print 'Without mentioning axis value\n'
print np.concatenate((a,b))
print '\nMentioning axis value 0 for the first dimension'
np.concatenate((a,b),axis=0)
Out[200]:
In [201]:
# Changing axis to point to second dimension by making axis = 1
np.concatenate((a,b),axis = 1)
Out[201]:
In [202]:
# Alternative way of creating array using arange() function
# If we mention only one single scalar value 'n' then it makes an array of 'n' starting from index 0
a = np.arange(7)
a
Out[202]:
In [203]:
# If we mention np.arange(x,y,increment) then it starts the array elements from x and y is exclusive.
# Increment value acts as a step value.
np.arange(1,10,2)
Out[203]:
In [204]:
# There are some functions like np.ones() and np.zeros() to create arrays having all values 1 and 0 respectively.
# We need to mention the number of elements and their type in the array
np.ones(8,dtype=float)
Out[204]:
In [205]:
# Multi-dimensional arrays can also be formed by mentioning number of rows and columns
np.zeros((3,2), dtype = int)
Out[205]:
In [206]:
# There are functions like np.zeros_like(arrayname) and np.ones_like(arrayname) to create new arrays like the exisitng ones
a = np.array([[2,3],[4,5]], dtype = int)
a
print a.shape
np.zeros_like(a)
Out[206]:
In [207]:
# Identity matrices can also be formed using np.identity() function by mentioning 'n' value as a parameter
np.identity(3,dtype = int)
Out[207]:
In [208]:
# Arithmetic operations on arrays are performed element-by-element. So in operations like addition or subtraction, the number
# of elements in the arrays should be same.
a = np.array([1,2,3])
b = np.array([4,5,6])
print a
print b
print 'After Addition :'
print a + b
In [209]:
print 'After Subtraction'
print b - a
In [210]:
print 'After Multiplication'
print a * b
In [211]:
print 'After Division'
print b/a
In [212]:
print 'After Modulo Operation'
print b%a
In [213]:
print 'Power operation'
print b**a
In [214]:
# For 2D arrays, multiplication operation remains element wise.
x = np.array([[1,2],[4,5]])
y = np.array([[10,4],[5,2]])
x * y
Out[214]:
In [215]:
# If arrays are not of same size, then error occurs.
a = np.array([51,42,78])
b = np.array([21,4])
In [216]:
# Arrays that do not have same dimsensions will be broadcasted by python to perform mathematical operations.
# smaller array will be repeated as necessary to perform the operation.
a = np.array([[1,2],[3,4],[5,6]])
b = np.array([[2,3]])
a + b
Out[216]:
In [217]:
# We can also add, subtract, multiply and divide scalar values element-wise
a = np.array([1,2,45,67,44,23,56,34])
print a
print 'After Addition'
print a + 2
print 'After Subtraction'
print a - 2
print 'After Multiplication'
print a * 2
print 'After Division'
print a/2
In [218]:
# There are several other operations that can be performed elementwise on numpy array
# Functions like ceil, floor, square, and sqrt are also available
# Considering an example for each
a = np.array([25,64,100])
print a
In [219]:
print 'Performing Square root'
print np.sqrt(a)
print 'Performing Square'
print np.square(a)
print np.sqrt(a).dtype
In [220]:
# Performing ceil and floor
a = np.array([1.5,4.8,6.7,8.9,2.1,3.7,9.9])
print a
print 'Ceil Operation'
print np.ceil(a)
print 'Floor Operation'
print np.floor(a)
In [221]:
# Rounding off the array elements
np.rint(a)
Out[221]:
In [222]:
# Array operations using built-in functions
# For obtaining sum of all the elements in the array, we use function arrayname.sum()
a = np.array([21,23,54,10,45,67,99])
a.sum()
Out[222]:
In [223]:
# For obtaining product of all the elements in the array, there is a function which can be called by arrayname.prod()
a.prod()
Out[223]:
In [224]:
# There are some standalone functions in NumPy for array operations
# For sum, np.sum() can be used
np.sum(a)
Out[224]:
In [225]:
# For product, np.prod() can be used
np.prod(a)
Out[225]:
In [226]:
# We also have functions to obtain mean and median
print 'Mean'
print np.mean(a)
print 'Median'
print np.median(a)
In [227]:
# We also have functions for obtaining variance and standard deviation
print 'Variance of Array'
print a.var()
print 'Standard Deviation of Array'
print a.std()
In [228]:
# To find maximum and minimum, we have functions called max() and min() respectively.
a.max()
Out[228]:
In [229]:
a.min()
Out[229]:
In [230]:
# We can also get array indices for maximum and minimum element using argmax() and argmin() respectively.
a.argmax()
Out[230]:
In [231]:
a.argmin()
Out[231]:
In [232]:
# We can also sort array elements using sorted() and sort() function
# sorted() returns list
print sorted(a)
print type(sorted(a))
In [233]:
# sort() - simply sorts the elements in the array
a.sort()
print a
In [234]:
# If we want values in the array to lie within a specified range, function called clip() can be used
a.clip(50,80)
Out[234]:
In [235]:
# To obtain correlation coefficient, we can use function np.corrcoef()
x = np.array([[20,23,45,46,50],[11,23,56,34,78]])
np.corrcoef(x)
Out[235]:
In [236]:
# We can obtain covariance value using function np.cov()
a = np.array([23,45,67,78])
np.cov(a)
Out[236]:
In [237]:
# To determine number of sistinct elements in the array, we can use unique() function of NumPy
a = np.array([11,2,2,3,5,11,6,5,7,8])
np.unique(a)
Out[237]:
In [238]:
# Array comparisons can also be done element wise
a = np.array([45,33,23,4,11,5])
b = np.array([2,33,22,4,10,5])
a == b
Out[238]:
In [239]:
a > 20
Out[239]:
In [240]:
a < 25
Out[240]:
In [241]:
(a > 10) & (a < 30)
Out[241]:
In [242]:
c = (a<=b)
c
Out[242]:
In [243]:
# We can use any() and all() function to check whether true value is present or not
print any(c)
print all(c)
In [244]:
all(np.array([1,2,3]) == np.array([1,2,3]))
Out[244]:
In [245]:
# We can also perform compound boolean expressions element-wise using np.logical_and(), np.logical_or() and np.logical_not().
a = np.array([23,45,6,7,8,12,34,2,1,5])
b = np.array([20,40,3,4,6,7,30,12,36,20])
np.logical_and(a > 20, a < 40)
Out[245]:
In [246]:
np.logical_or(a > 20, a < 40)
Out[246]:
In [247]:
np.logical_not(a > 10)
Out[247]:
In [248]:
# To determine the indices of array where the value is nonzero.
a = np.array([1,2,0,4,5,0,7,9,0,5])
print a.nonzero()
print type(a.nonzero())
In [249]:
a = np.array([11,15,56,23,20,10,8,4])
print np.where(a>10,1,0)
print sum(np.where(a>10,1,0))
In [250]:
# We can also use functions np.isnan() and np.isfinite() to check NA and Infinite values
a = np.array([1,2,np.NaN,3,6,np.Inf])
print a
np.isnan(a)
Out[250]:
In [251]:
np.isfinite(a)
Out[251]:
In [252]:
np.isinf(a)
Out[252]:
In [253]:
# Checking for elements within specific range for 2D arrays
a = np.array([[4,5,6,7],[34,30,67,89],[23,20,45,33]])
print a
a[(a>10)&(a<30)]
Out[253]:
In [254]:
(a>10)&(a<35)
Out[254]:
In [255]:
# We can also perform selection of some specific values with arrays as indices
a = np.array([56,45,40,99,100,105,44,34])
b = np.array([1,2,5,6,3,4])
print a
print 'Indices Array :'
print b
a[b]
Out[255]:
In [256]:
# There is a function called take() which is used in similar manner for selection like the above approach
# We can also mention axis value for 2D arrays. - take(indices_array, axis)
a.take(b)
Out[256]:
In [257]:
# We also have put() function to place some values at specific positions.
a.put([1,2,4],0)
print a
In [258]:
# Here the source will be repeated if necessary
a.put([0,3,4],[5,6,7])
print a
In [259]:
# NumPy has some built-in functions for vector and array mathematics.
# Considering two numpy one dimensional arrays and obtaining dot product using np.dot() function
a = np.array([11,2,33,5])
b = np.array([1,12,2,10])
print a
print b
print 'Dot Product of a and b'
np.dot(a,b)
Out[259]:
In [260]:
# For 2D NumPy array, using dot() function is similar to matrix multiplication
a = np.array([[10,11],[4,5]])
b = np.array([2,3])
np.dot(b,a)
Out[260]:
In [261]:
np.dot(a,b)
Out[261]:
In [262]:
# Numpy also has functions for inner, outer and cross product of vectors and matrices.
# For vectors, inner product is same as dot product.
print np.inner(a,b)
print np.dot(a,b)
In [263]:
# For outer product, we use numpy.outer() function
np.outer(a,b)
Out[263]:
In [265]:
# Cross Product for matrices and vectors can be obtained using function numpy.cross().
a = np.array([1,4,5])
b = np.array([2,3,6])
np.cross(a,b)
Out[265]:
In [266]:
# NumPy also has built-in functions for linear algebra calculations
# There is a subpackage called 'numpy.linalg' which provides functions for vector and matrix arithmetics
# Considering a matrix and obtaining determinant, rank and sign and natural logarithm of determinant of matrix.
a = np.array([[10,20],[35,45]])
# To obtain determinant of matrix, we use function numpy.linalg.det().
np.linalg.det(a)
Out[266]:
In [269]:
# Obtaining rank of matrix (number of independent vectors) can be obtained using numpy.linalg.matrix_rank()
# Here first two rows are dependent as second row can be obtained by multiplying each element of first row by 2.
a = np.array([[12,13,14],[24,26,28],[1,2,3]])
print a
np.linalg.matrix_rank(a)
Out[269]:
In [273]:
# We can also obtain trace of matrix (Sum of elements across diagonal) using function numpy.trace()
# There are parameters like offset, axis, dtype and out.
np.trace(a)
Out[273]:
In [274]:
# Condition number of matrix can be obtained using function numpy.linalg.cond().
# In numerical analysis, this number plays very important role in getting initial insights about matrix.
# This number indicates the change in output values for small change in input values
np.linalg.cond(a)
Out[274]:
In [276]:
# Determining sign and natural logarithm of determinant of matrix
np.linalg.slogdet(a)
Out[276]:
In [277]:
# This function returns one of norms out of eight different matrix norms or one out of an infinite number of vector norms
# depending on the arguments.
np.linalg.norm(a)
Out[277]:
In [288]:
# Eigen values and right eigen vectors of square array using functions numpy.linalg.eig().
# To obtain only eigen values of a general matrix, we use function numpy.linalg.eigvals()
a = np.array([[2,3],[10,11]])
print a
print 'Eigen Values and Eigen Vectors'
print np.linalg.eig(a)
print 'Eigen Values'
print np.linalg.eigvals(a)
In [289]:
# To obtain eigen values and eigen vectors of symmetric or hermitian matrix, we use function numpy.linalg.eigh()
# To obtain eigen values of a symmetric or hermitian matrix, we use function numpy.linalg.eigvalsh()
a = np.array([[1,4,5],[4,2,6],[5,6,3]])
print a
print 'Eigen Values and Eigen Vectors'
np.linalg.eigh(a)
print 'Eigen Values'
np.linalg.eigvalsh(a)
Out[289]:
In [292]:
# Solving system of linear scalar equations using function numpy.linalg.solve()
a = np.array([[2,3],[1,2]])
b = np.array([[3,4],[5,6]])
np.linalg.solve(a,b)
Out[292]:
In [293]:
# Obtaining inverse of matrix using function numpy.linalg.inv()
np.linalg.inv(a)
Out[293]:
In [294]:
# NumPy also have some functions to deal with polynomials
# If we give set of roots to function np.poly(), it returns possible coefficients
np.poly([1,2])
Out[294]:
In [295]:
# We can perform opposite operation to obtain roots of polynomial by passing coefficients to function np.roots()
np.roots([1,-3,2])
Out[295]:
In [308]:
# For polynomials, we can perform integration and differentiation using functions numpy.polyint() and numpy.polyder()
# respectively.
# Polynomial becomes x^3 + 2*x^2 + 4*x + 3
inte = np.polyint([1,2,4,3])
inte
Out[308]:
In [309]:
# Using function numpy.polyder() for obtaining derivation of the same polynomial from its integration
der = np.polyder(inte)
der
Out[309]:
In [307]:
# We can solve some polynomial for particular value by using function numpy.polyval()
# Here it takes coefficients of the polynomial and the value for which to solve as an input.
# Polynomial becomes x^2 + x + 1 and value of x = 2 results value 7
np.polyval([1,1,1],2)
Out[307]:
In [310]:
# There are functions like numpy.polyadd(), numpy.polysub(), numpy.polymul() and numpy.polydiv() for addition, subtraction,
# multiplication and division respectively.
# Showing an example for addition here. Other functions can be explored in similar manner.
a = np.array([1,2,3])
b = np.array([4,5,6])
np.polyadd(a,b)
Out[310]:
In [311]:
# Dealing with generation of random numbers using numpy subpackage numpy.random
# Using np.random.seed() to obtain same sequence of random numbers at different points in program
# Using same seed value ensures to generating same sequence of random numbers which is useful in debugging purpose
np.random.seed(5)
In [312]:
# We can generate array of random numbers in half-open interval [0.0, 1) using function np.random.rand()
np.random.rand(5)
Out[312]:
In [313]:
# To genrate a single random number, we use fumction np.random.random() in interval [0,1).
np.random.random()
Out[313]:
In [314]:
# 2D arrays can be generated by mentioning dimensions as input.
# Can also use reshape() function to set the dimensions appropriately.
np.random.rand(4,5)
Out[314]:
In [ ]: