-
Introduction to NumPy and NumPy installation
INTRODUCTION TO NUMPY:
NumPy is a Python package. It stands for 'Numerical Python'. It is a library consisting of multidimensional array objects and a collection of routines for processing of array.
Operations using NumPy
Using NumPy, a developer can perform the following operations:- Mathematical and logical operations on arrays.
- Fourier transforms and routines for shape manipulation.
- Operations related to linear algebra. NumPy has in-built functions for linear algebra and random number generation.
Standard Python distribution doesn't come bundled with NumPy module. A lightweight alternative is to install NumPy using popular Python package installer, pip.
To install NumPy follow the steps (in Windows):- Open command prompt and set current working directory as C:\Users\UserName\AppData\Local\Programs\Python\Python310\Scripts>
- Then enter the following command pip install numpy
- After completion of package installation test the code import numpy
NUMPY – BASICS:
- np.arange():
The arange() function is used to get evenly spaced values within a given interval. Values are generated within the half-open interval [start, stop]. For integer arguments the function is equivalent to the Python built-in range function, but returns an ndarray rather than a list.
Syntax:
numpy.arange([start, ]stop, [step, ]dtype=None)Example:
import numpy as npOutput:
oddnos = np.arange(1,10,+2)
print(oddnos)
[1 3 5 7 9] - numpy.linspace():
This function returns evenly spaced numbers over a specified interval.
Syntax:
numpy.linspace(start, stop, num=50, endpoint=True, retstep=False, dtype=None, axis=0)start - The starting value of the sequence.
Example:
stop - The end value of the sequence, unless endpoint is set to False. In that case, the sequence consists of all but the last of num + 1 evenly spaced samples, so that stop is excluded. Note that the step size changes when endpoint is False.
num - Number of samples to generate. Default is 50. Must be non-negative.
endpoint - If True, stop is the last sample. Otherwise, it is not included. Default is True.
retstep - If True, return (samples, step), where step is the spacing between samples.
dtyped - The type of the output array. If dtype is not given, the data type is inferred from start and stop. The inferred dtype will never be an integer; float is chosen even if the arguments would produce an array of integers.
axis - The axis in the result to store the samples. Relevant only if start or stop are array-like. By default (0), the samples will be along a new axis inserted at the beginning. Use -1 to get an axis at the end.
import numpy as npOutput:
fractions = np.linspace(1,2,num=5,retstep=True)
print(fractions)
(array([1. , 1.25, 1.5 , 1.75, 2. ]), 0.25) - numpy.random.random():
This function of random module is used to generate random floats number in the half-open interval (0.0, 1.0).
Syntax:
numpy.random.random([size])Example:
import numpy as npOutput:
print("Random element is:\n",np.random.random())
print("Array of random elements is:\n",np.random.random(4))
Random element is:
0.8263791060448403
Array of random elements is:
array([0.2147186 , 0.18682856, 0.39970985, 0.66319872])
-
NumPy - Data Types
NUMPY – DATA TYPES:
By default Python have these data types:
- strings - used to represent text data.
- integer - used to represent integer numbers.
- float - used to represent real numbers.
- boolean - used to represent True or False.
- complex - used to represent complex numbers.
NumPy has some extra data types, and refer to data types with following character:
- i - integer
- b - boolean
- u - unsigned integer
- f - float
- c - complex float
- m - timedelta
- M - datetime
- O - object
- S - string
- U - unicode string
- V - fixed chunk of memory for other type (void)
The NumPy array object has a property called dtype that returns the data type of the array.
The astype() function creates a copy of the array, and allows you to specify the data type as a parameter.
-
NumPy - Arrays
NUMPY - ARRAYS:
NumPy is an N-dimensional array type called ndarray. It describes the collection of items of the same type. Items in the collection can be accessed using a zero-based index.
Syntax:
The basic ndarray is created using an array function in NumPy as follows −
numpy.array(object, dtype = None, copy = True, order = None, subok = False, ndmin = 0)object - Any object exposing the array interface method returns an array, or any (nested) sequence.
Example:
dtype - Desired data type of array, optional
copy - Optional. By default (true), the object is copied
order - C (row major) or F (column major) or A (any) (default)
subok - By default, returned array forced to be a base class array. If true, sub-classes passed through.
ndmin - Specifies minimum dimensions of resultant array.
import numpy as npOutput:
cars = np.array(["Tata","BMW","Maruthi"])
print(cars)
['Tata' 'BMW' 'Maruthi']ARRAY ATTRIBUTES:
-
ndarray.shape - This array attribute returns a tuple consisting of array dimensions. It can also be used to resize the array.
Example:
import numpy as npOutput:
#Creating 2X3 matrix
mtrx = np.array([[1,2,3],[4,5,6]])
print(mtrx)
#Shape of matrix
print("Shape of matrix is :",mtrx.shape)
[[1 2 3]
[4 5 6]]
Shape of matrix is : (2, 3)
This attribute is also used to resize the ndarray.
Example:
import numpy as npOutput:
#Creating 2X3 matrix
mtrx = np.array([[1,2,3],[4,5,6]])
print(mtrx)
#Shape of matrix
print("Shape of matrix is :",mtrx.shape)
#Resize the matrix using shape attribute
print("Resizing the matrix")
mtrx.shape = (3,2)
print(mtrx)
[[1 2 3]
[4 5 6]]
Shape of matrix is : (2, 3)
Resizing the matrix
[[1 2]
[3 4]
[5 6]]
NumPy also provides a reshape function to resize an array.
Example:
import numpy as npOutput:
#Creating 2X3 matrix
mtrx = np.array([[1,2,3],[4,5,6]])
print(mtrx)
#Shape of matrix
print("Shape of matrix is :",mtrx.shape)
mtrx2 = mtrx.reshape(3,2)
print(mtrx2)
[[1 2 3]
[4 5 6]]
Shape of matrix is : (2, 3)
[[1 2]
[3 4]
[5 6]]
ndarray.ndim - This array attribute returns the number of array dimensions.
Example:
import numpy as npOutput:
mtrx = np.array([[1,2,3],[4,5,6]])
print(mtrx.ndim)
2ndarray.itemsize - This array attribute returns the length of each element of array in bytes.
Example:
import numpy as npOutput:
mtrx = np.array([[1,2,3],[4,5,6]],dtype=int)
print(mtrx.itemsize)
4
NUMPY - ARRAY CREATION ROUTINES:
A new ndarray object can be constructed by any of the following array creation routines or using a low-level ndarray constructor.
numpy.empty - It creates an uninitialized array of specified shape and dtype.
Syntax:
numpy.empty(shape, dtype = float, order = 'C')Shape - Shape of an empty array in int or tuple of int
Example:
Dtype - Desired output data type. Optional
Order - 'C' for C-style row-major array, 'F' for FORTRAN style column-major array
import numpy as npOutput:
defAry = np.empty([3,2],dtype=int,order='C')
print(defAry)
[[0 0]
[0 0]
[0 0]]
numpy.zeros -Returns a new array of specified size, filled with zeros.
Syntax:
numpy.zeros(shape, dtype = float, order = 'C')Shape - Shape of an empty array in int or tuple of int
Example:
Dtype - Desired output data type. Optional
Order - 'C' for C-style row-major array, 'F' for FORTRAN style column-major array
import numpy as npOutput:
allZeros = np.zeros([3,3],dtype=int)
print(allZeros)
[[0 0 0]
[0 0 0]
[0 0 0]]
numpy.ones - Returns a new array of specified size and type, filled with ones.
Syntax:
numpy.ones(shape, dtype = None, order = 'C')Shape - Shape of an empty array in int or tuple of int
Example:
Dtype - Desired output data type. Optional
Order - 'C' for C-style row-major array, 'F' for FORTRAN style column-major array
import numpy as npOutput:
allOnes = np.ones([7],dtype=int)
print(allOnes)
[1 1 1 1 1 1 1]
-
-
Numpy - Array Manipulation
NUMPY ARRAY MANIPULATION:
numpy.append(): This function adds values at the end of an input array. The append operation is not in-place, a new array is allocated. Also the dimensions of the input arrays must match otherwise ValueError will be generated.
Syntax:
numpy.append(arr, values, axis)arr - Input array
Example:
values - To be appended to arr. It must be of the same shape as of arr (excluding axis of appending)
axis - The axis along which append operation is to be done. If not given, both parameters are flattened
import numpy as npOutput:
ary = np.array([5,10,15,20])
ary = np.append(ary,[25,30])
print(ary)
[ 5 10 15 20 25 30]numpy.insert(): This function inserts values in the input array along the given axis and before the given index. If the type of values is converted to be inserted, it is different from the input array. Insertion is not done in place and the function returns a new array.
Syntax:
numpy.insert(arr, obj, values, axis)arr - Input array
Example:
obj - The index before which insertion is to be made
values - The array of values to be inserted
axis - The axis along which to insert. If not given, the input array is flattened
import numpy as npOutput:
ary = np.array([5,10,15,20])
ary = np.insert(ary,2,13)
print(ary)
[ 5 10 13 15 20]numpy.resize(): This function returns a new array with the specified size. If the new size is greater than the original, the repeated copies of entries in the original are contained.
Syntax:
numpy.resize(arr, shape)arr - Input array to be resized
Example:
shape - New shape of the resulting array
import numpy as npOutput:
mtrx = np.array([[1,2,3],[4,5,6]])
mtrx = np.resize(mtrx,(3,3))
print(mtrx)
[[1 2 3]
[4 5 6]
[1 2 3]]
numpy.delete(): This function returns a new array with the specified subarray deleted from the input array.
Syntax:
numpy.delete(arr, obj, axis)arr - Input array
Example:
obj - Can be a slice, an integer or array of integers, indicating the subarray to be deleted from the input array
axis - The axis along which to delete the given subarray. If not given, arr is flattened
import numpy as npOutput:
mtrx = np.array([[1,2,3],[4,5,6]])
mtrx = np.delete(mtrx,1,axis=1)
print(mtrx)
[[1 3]
[4 6]]
numpy.concatenate(): This function is used to join two or more arrays of the same shape along a specified axis.
Syntax:
numpy.concatenate((a1, a2, ...), axis)a1,a2.. - Sequence of arrays of the same type
Example:
axis - Axis along which arrays have to be joined. Default is 0
import numpy as npOutput:
ary1 = np.array([1,3,5])
ary2 = np.array([2,4,6])
ary3 = np.concatenate((ary1,ary2))
print(ary3)
[1 3 5 2 4 6]numpy.stack(): This function joins the sequence of arrays along a new axis.
Syntax:
numpy.stack(arrays, axis)arrays - Sequence of arrays of the same shape
Example:
axis - Axis in the resultant array along which the input arrays are stacked
import numpy as npOutput:
ary1 = np.array([1,3,5])
ary2 = np.array([2,4,6])
stack = np.stack((ary1,ary2),axis=0)
print(stack)
[[1 3 5]
[2 4 6]]
numpy.hstack(): This function joins the sequence of arrays into single array horizontally.
Syntax:
numpy.hstack(arrays)Example:
import numpy as npOutput:
mtrx1 = np.array([[1,2],[3,4]])
mtrx2 = np.array([[5,6],[7,8]])
HStack = np.hstack((mtrx1,mtrx2))
print(HStack)
[[1 2 5 6]
[3 4 7 8]]
numpy.vstack(): This function joins the sequence of arrays into single array vertically.
Syntax:
numpy.vstack(arrays)Example:
import numpy as npOutput:
mtrx1 = np.array([[1,2],[3,4]])
mtrx2 = np.array([[5,6],[7,8]])
VStack = np.vstack((mtrx1,mtrx2))
print(VStack)
[[1 2]
[3 4]
[5 6]
[7 8]]
-
NumPy - Mathematical Functions
NUMPY - MATHEMATICAL FUNCTIONS
NumPy contains a large number of various mathematical operations arithmetic operations, trigonometric functions, handling complex numbers, etc.
Arithmetic Operations:
- numpy.add() – Performs addition operation.
- numpy.subtract() – Performs subtraction operation.
- numpy.multiply() – Performs multiplication operation.
- numpy.divide() – Performs division operation.
import numpy as npOutput:
ary1 = np.array([[1,2,3],[4,5,6],[7,8,9]])
ary2 = np.array([1,2,3])
print("First array:\n",ary1)
print("Second array:\n",ary2)
print("Addition of array1 and array2:\n",np.add(ary1,ary2))
print("Subtraction of array1 and array2:\n",np.subtract(ary1,ary2))
print("Multiplication of array1 and array2:\n",np.multiply(ary1,ary2))
print("Division of array1 and array2:\n",np.divide(ary1,ary2))
First array:Trigonometric Functions
[[1 2 3]
[4 5 6]
[7 8 9]]
Second array:
[1 2 3]
Addition of array1 and array2:
[[ 2 4 6]
[ 5 7 9]
[ 8 10 12]]
Subtraction of array1 and array2:
[[0 0 0]
[3 3 3]
[6 6 6]]
Multiplication of array1 and array2:
[[ 1 4 9]
[ 4 10 18]
[ 7 16 27]]
Division of array1 and array2:
[[1. 1. 1. ]
[4. 2.5 2. ]
[7. 4. 3. ]]
NumPy has standard trigonometric functions which return trigonometric ratios for a given angle in radians.
- numpy.sin()
- numpy.cos()
- numpy.tan()
import numpy as npOutput:
ary = np.array([0,30,45,60,90])
sine = np.sin(ary*np.pi/180)
print("Sine values:\n",sine)
cosine = np.cos(ary*np.pi/180)
print("Cosine values:\n",cosine)
tangent = np.tan(ary*np.pi/180)
print("Tangent values:\n",tangent)
Sine values:
[0. 0.5 0.70710678 0.8660254 1. ]
Cosine values:
[1.00000000e+00 8.66025404e-01 7.07106781e-01 5.00000000e-01 6.12323400e-17]
Tangent values:
[0.00000000e+00 5.77350269e-01 1.00000000e+00 1.73205081e+00 1.63312394e+16]
-
NumPy - Statistical Functions
NUMPY - STATISTICAL FUNCTIONS
numpy.mean() - Arithmetic mean is the sum of elements along an axis divided by the number of elements. The numpy.mean() function returns the arithmetic mean of elements in the array. If the axis is mentioned, it is calculated along it.
Syntax:
numpy.mean(array,axis)numpy.median() - Median is defined as the value separating the higher half of a data sample from the lower half.
Syntax:
numpy.median(array,axis)numpy.std() - Standard deviation is the square root of the average of squared deviations from mean, i.e. sqrt(mean(abs(x - x.mean())**2))
Syntax:
numpy.std(array)numpy.var() - Variance is the average of squared deviations, i.e., mean(abs(x - x.mean())**2).
Syntax:
numpy.var(array)
import numpy as npOutput:
ary = np.array([2,4,6,8,10])
print("Array is:\n",ary)
mean = np.mean(ary)
print("Mean is:\n",mean)
median = np.median(ary)
print("Median is:\n",median)
std = np.std(ary)
print("Standard Deviation is:\n",std)
var = np.var(ary)
print("Variance is:\n",var)
Array is:
[ 2 4 6 8 10]
Mean is:
6.0
Median is:
6.0
Standard Deviation is:
2.8284271247461903
Variance is:
8.0
-
NumPy - String Functions
NUMPY – STRING FUNCTIONS:
numpy.char.title(): Returns element-wise title cased string.
numpy.char.lower(): Returns string converted into lower-case.
numpy.char.upper(): Returns string converted into upper-case.
numpy.char.split(): Returns the list of words in the string using separator delimiter.
numpy.char.strip(): Returns a copy with the leading and trailing characters removed.
numpy.char.join(): Returns a string which is the concatenation of the strings in the sequence.
numpy.char.encode(): Returns a encoded string.
numpy.char.decode(): Returns a decoded string from encoded string.
import numpy as npOutput:
string = "Hello how are you"
print("String is:\n",string)
print("Title case string is:\n",np.char.title(string))
print("String in lower-case is:\n",np.char.lower(string))
print("String in upper-case is:\n",np.char.upper(string))
print("Spliting String:\n",np.char.split(string))
print("String Strip:\n",np.char.strip(string,'u'))
print("join('-','dmy'):\n",np.char.join('-','dmy'))
encodeString = np.char.encode(string,'cp500')
print("Encoded string is:\n",encodeString)
print("Decoded string is:\n",np.char.decode(encodeString,'cp500'))
String is:
Hello how are you
Title case string is:
Hello How Are You
String in lower-case is:
hello how are you
String in upper-case is:
HELLO HOW ARE YOU
Spliting String:
['Hello', 'how', 'are', 'you']
String Strip:
Hello how are yo
join('-','dmy'):
d-m-y
Encoded string is:
b'\xc8\x85\x93\x93\x96@\x88\x96\xa6@\x81\x99\x85@\xa8\x96\xa4'
Decoded string is:
Hello how are you