Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
11 views

Module Numpy

The document discusses NumPy, a Python library used for working with multidimensional arrays and matrices for numerical processing. NumPy allows fast operations on arrays and matrices and has extensive support for linear algebra, Fourier transforms, and random number generation. NumPy arrays can be created in various ways and allow indexing, slicing, and shape manipulation for accessing and modifying elements.

Uploaded by

Aamna Raza
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
11 views

Module Numpy

The document discusses NumPy, a Python library used for working with multidimensional arrays and matrices for numerical processing. NumPy allows fast operations on arrays and matrices and has extensive support for linear algebra, Fourier transforms, and random number generation. NumPy arrays can be created in various ways and allow indexing, slicing, and shape manipulation for accessing and modifying elements.

Uploaded by

Aamna Raza
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 67

Python-Module

Numpy
Introduction
• NumPy stands for Numerical Python which is a Python package
developed by Travis Oliphant in 2005.
• It is a library consisting of multidimensional array objects and a
collection of routines for performing mathematical and logical
operations on those arrays.
• NumPy Environment Setup
NumPy doesn't come bundled with Python. We have to install it using the
python pip installer. Execute the following command.
$ pip install numpy

3
In Python, we use the list for purpose of the array but it’s slow to
process. There are the following advantages of using NumPy for data
analysis.
• NumPy performs array-oriented computing.
• It efficiently implements the multidimensional arrays.
• It performs scientific computations.
• It is capable of performing Fourier Transform and reshaping the
data stored in multidimensional arrays.
• NumPy provides the in-built functions for linear algebra and
random number generation.

4
Introduction
• Before using the objects and routines available in Numpy we have to
write any one of the following command:
• import numpy
• import numpy as np
• from numpy import *

5
Arrays in Numpy
Array in Numpy is a table of elements (usually numbers), all of
the same type, indexed by a tuple of positive integers.
In Numpy, the number of dimensions of the array is called rank
of the array.
A tuple of integers giving the size of the array along each
dimension is known as shape of the array.
An array class in Numpy is called as ndarray.
Elements in Numpy arrays are accessed by using square brackets
and can be initialized by using nested Python Lists.

6
Example 1: 1-D Array
# importing numpy module
import numpy as np
# creating list
Output:
list = [1, 2, 3, 4]
# creating numpy array List in python : [1, 2, 3, 4]
sample_array = np.array(list1) Numpy Array in python : [1 2 3 4]
<class 'list'>
print("List in python : ", list)
<class 'numpy.ndarray'>
print("Numpy Array in python :", sample_array)
print(type(list))
print(type(sample_array))

7
Example: multi-dimensional Array
# importing numpy module
import numpy as np Output:

# creating list Numpy multi dimensional array in python


list_1 = [1, 2, 3, 4] [[ 1 2 3 4]
[ 5 6 7 8]
list_2 = [5, 6, 7, 8] [ 9 10 11 12]]
list_3 = [9, 10, 11, 12] Note: use [ ] operators inside numpy.array() for
multi-dimensional
# creating numpy array
sample_array = np.array([list_1, list_2, list_3])
print("Numpy multi dimensional array in python\n", sample_array)

8
Example: Shape: The number of elements along with each dimension.
# importing numpy module
import numpy as np
# creating list
list_1 = [1, 2, 3, 4]
list_2 = [5, 6, 7, 8] Output:
list_3 = [9, 10, 11, 12]
Numpy array :
# creating numpy array [[ 1 2 3 4]
sample_array = np.array([list_1, list_2, list_3]) [ 5 6 7 8]
[ 9 10 11 12]]
print(sample_array)
Shape of the array : (3, 4)
# print shape of the array
print("Shape of the array :", sample_array.shape)

9
Example: shape
import numpy as np
sample_array = np.array([[0, 4, 2],
[3, 4, 5],
[23, 4, 5],
[2, 34, 5],
[5, 6, 7]])

print("shape of the array :", sample_array.shape)


Output:
shape of the array : (5, 3)

10
Data type objects (dtype): Data type objects (dtype) is an instance
of numpy.dtype class. It describes how the bytes in the fixed-size block of memory
corresponding to an array item should be interpreted.

Example:
# Import module
import numpy as np
# Creating the array
sample_array_1 = np.array([[0, 4, 2]]) Output:
sample_array_2 = np.array([0.2, 0.4, 2.4])
Data type of the array 1 : int32
# display data type Data type of array 2 : float64
print("Data type of the array 1 :", sample_array_1.dtype)
print("Data type of array 2 :", sample_array_2.dtype)

11
Some different way of creating Numpy Array :
1. numpy.array(): The Numpy array object in Numpy is called ndarray. We can create
ndarray using numpy.array() function.
Syntax: numpy.array(parameter)
# import module
import numpy as np
#creating an array
arr = np.array([3,4,5,5])
print("Array :",arr)
Output:
Array : [3 4 5 5]

12
2. numpy.fromiter(): The fromiter() function create a new one-dimensional array from
an iterable object.
Syntax: numpy.fromiter(iterable, dtype, count=-1)
#Import numpy module
import numpy as np
# iterable
iterable = (a*a for a in range(8))
arr = np.fromiter(iterable, int)
print("fromiter() array :",arr)

Output:
fromiter() array : [ 0 1 4 9 16 25 36 49]

13
Numpy-Array Creation from functions
• There are multiple ways to create array of single/multi dimensions
through Numpy. Those are
• array()
• empty()
• zeros()
• ones()
• arrange()
• linspace()
• logspace()
• asarray()

14
3. numpy.arange(): This is an inbuilt NumPy function that returns evenly spaced values
within a given interval.
Syntax: numpy.arange([start, ]stop, [step, ]dtype=None)

import numpy as np
np.arange(1, 20 , 2)

Output:
array([ 1, 3, 5, 7, 9, 11, 13, 15, 17, 19])

15
4. numpy.linspace(): This function returns evenly spaced numbers over a specified
between two limits.
Syntax: numpy.linspace(start, stop, num=10)
-> start : [optional] start of interval range. By default start = 0
-> stop : end of interval range
-> num : [int, optional] No. of samples to generate

import numpy as np
np.linspace(1, 10, 10)

Output:
array([ 1., 2., 3., 4., 5., 6., 7., 8., 9., 10.])

16
5. numpy.empty(): This function create a new array of given shape and type, without
initializing value.
Syntax: numpy.empty(shape, dtype=float, order=’C’)
order: {'C', 'F'}(optional)
This parameter defines the order in which the multi-dimensional array is going to be
stored either in row-major or column-major. By default, the order parameter is set to
'C'.
import numpy as np
np.empty([4, 3], dtype = np.int32, order = 'f')

Output:
array([[ 1, 5, 9],
[ 2, 6, 10],
[ 3, 7, 11],
[ 4, 8, 12]])

17
6. numpy.ones(): This function is used to get a new array of given shape and type, filled
with ones(1).
Syntax: numpy.ones(shape, dtype=None, order=’C’)

import numpy as np
np.ones([4, 3], dtype = np.int32, order = 'f')

Output:

array([[1, 1, 1],
[1, 1, 1],
[1, 1, 1],
[1, 1, 1]])

18
7. numpy.zeros(): This function is used to get a new array of given shape and type,
filled with zeros(0).
Syntax: numpy.zeros(shape, dtype=None)

Example:
import numpy as np
np.zeros([4, 3], dtype = np.int32, order = 'f')
Output:

array([[0, 0, 0],
[0, 0, 0],
[0, 0, 0],
[0, 0, 0]])

19
Accessing the array Index
• In a numpy array, indexing or accessing the array index can be
done in multiple ways.
• To print a range of an array, slicing is done. Slicing of an array is
defining a range in a new array which is used to print a range of
elements from the original array.
• Since, sliced array holds a range of elements of the original
array, modifying content with the help of sliced array modifies
the original array content.

20
# Python program to demonstrate indexing in numpy array
import numpy as np Output:
arr = np.array([[-1, 2, 0, 4], Initial Array:
[[-1. 2. 0. 4. ]
[4, -0.5, 6, 0], [ 4. -0.5 6. 0. ]
[ 2.6 0. 7. 8. ]
[2.6, 0, 7, 8],
[ 3. -7. 4. 2. ]]
[3, -7, 4, 2.0]]) Array with first 2 rows and alternate
columns(0 and 2):
print("Initial Array: ")
[[-1. 0.]
print(arr) [ 4. 6.]]
# Printing a range of Array with the use of slicing methodElements at indices (1, 3), (1, 2), (0, 1), (3, 0):
sliced_arr = arr[:2, ::2] [ 0. 54. 2. 3.]
print ("Array with first 2 rows and“ " alternate columns(0 and 2):\n", sliced_arr)
# Printing elements at specific Indices
Index_arr = arr[[1, 1, 0, 3], [3, 2, 1, 0]]
print ("\nElements at indices (1, 3), (1, 2), (0, 1), (3, 0):\n", Index_arr)
21
Basic Array Operations

In numpy, arrays allow a wide range of operations which can be


performed on a particular array or a combination of Arrays.
These operation include some basic Mathematical operation as
well as Unary and Binary operations.

22
# Python program to demonstrate basic operations on single array
import numpy as np
# Defining Array 1 Output:
a = np.array([[1, 2], [3, 4]])
Adding 1 to every element:
# Defining Array 2 [[2 3]
b = np.array([[4, 3], [2, 1]]) [4 5]]
# Adding 1 to every element Subtracting 2 from each element:
print ("Adding 1 to every element:", a + 1) [[ 2 1]
[ 0 -1]]
# Subtracting 2 from each element
print ("\nSubtracting 2 from each element:", b - 2) Sum of all array elements: 10

# sum of array elements Array sum:


# Performing Unary operations [[5 5]
[5 5]]
print ("\nSum of all array elements: ", a.sum())
# Adding two arrays Performing Binary operations
print ("\nArray sum:\n", a + b) 23
Math Operations on DataType array

In Numpy arrays, basic mathematical operations are performed


element-wise on the array. These operations are applied both as
operator overloads and as functions.
Many useful functions are provided in Numpy for performing
computations on Arrays such as sum: for addition of Array
elements, T: for Transpose of elements, etc.

24
# Python Program to create a data type object
import numpy as np
arr1 = np.array([[4, 7], [2, 6]], dtype = np.float64)
arr2 = np.array([[3, 6], [2, 8]], dtype = np.float64)
Output:
Sum = np.add(arr1, arr2) # Addition of two Arrays Addition of Two Arrays:
print("Addition of Two Arrays: “, Sum) [[ 7. 13.]
# Addition of all Array elements using predefined sum method [ 4. 14.]]
Sum1 = np.sum(arr1)
Addition of Array elements:
print("\nAddition of Array elements: “, Sum1) 19.0
# Square root of Array
Sqrt = np.sqrt(arr1) Square root of Array1 elements:
[[2. 2.64575131]
print("\nSquare root of Array1 elements: “, Sqrt)
[1.41421356 2.44948974]]
# Transpose of Array using In-built function 'T'
Trans_arr = arr1.T Transpose of Array:
print("\nTranspose of Array: “, Trans_arr) [[4. 2.]
[7. 6.]]

25
Trigonometric Functions

• NumPy has standard trigonometric functions which return


trigonometric ratios for a given angle in radians.

26
import numpy as np
a = np.array([0,30,45,60,90])
print 'Sine of different angles:'
# Convert to radians by multiplying with pi/180
print(np.sin(a*np.pi/180)) Output:
Sine of different angles:
print('Cosine values for angles in array:') [ 0. 0.5 0.70710678 0.8660254 1. ]
print(np.cos(a*np.pi/180))
Cosine values for angles in array:
print('Tangent values for given angles:') [ 1.00000000e+00 8.66025404e-01 7.07106781e-01
print(np.tan(a*np.pi/180)) 5.00000000e-01
6.12323400e-17]

Tangent values for given angles:


[ 0.00000000e+00 5.77350269e-01 1.00000000e+00
1.73205081e+00
1.63312394e+16]

27
arcsin, arcos, and arctan functions return the trigonometric
inverse of sin, cos, and tan of the given angle. The result of these
functions can be verified by numpy.degrees() function by
converting radians to degrees.

28
import numpy as np
a = np.array([0,30,45,60,90])
Print ( 'Array containing sine values:' )
sin = np.sin(a*np.pi/180)
print (sin )
print 'Compute sine inverse of angles. Returned values are in radians.'
inv = np.arcsin(sin)
print (inv)
print 'Check result by converting to degrees:'
print (np.degrees(inv) )
Print ('arccos and arctan functions behave similarly:‘)
cos = np.cos(a*np.pi/180)
print (cos)
print 'Inverse of cos:'
inv = np.arccos(cos)
print (inv)
print 'In degrees:'
print (np.degrees(inv) )
print ('Tan function:‘)
tan = np.tan(a*np.pi/180)
print (tan)
print ('Inverse of tan:' )
inv = np.arctan(tan)
print (inv )
print 'In degrees:'
print (np.degrees(inv) )

29
Functions for Rounding

1. numpy.around()
This is a function that returns the value rounded to the desired
precision. The function takes the following parameters.
numpy.around(a,decimals)
2. numpy.floor()
This function returns the largest integer not greater than the
input parameter. The floor of the scalar x is the largest integer i,
such that i <= x. Note that in Python, flooring always is rounded
away from 0.
30
3. numpy.ceil()
The ceil() function returns the ceiling of an input value, i.e. the
ceil of the scalar x is the smallest integer i, such that i >= x.

31
Numpy-Array- Attributes
• ndarray.shape
• This array attribute returns a tuple consisting of array dimensions. It can also be
used to resize the array.
• ndarray.ndim
• This array attribute returns the number of array dimensions.
• numpy.itemsize
• This array attribute returns the length of each element of array in bytes.

32
Numpy-Array- Attributes
from numpy import *
a=array([[1.1,2,3],[4,5,6]])
Output:
print(a)
[[1.1 2. 3. ]
print(a.shape) [4. 5. 6. ]]
print(a.ndim) (2, 3)
2
print(a.itemsize) 8
a.shape=(3,2) (3, 2)
2
print(a.shape)
8
print(a.ndim) [[1.1 2. ]
print(a.itemsize) [3. 4. ]
[5. 6. ]]
print(a)

33
Numpy-Array- Indexing & Slicing
• Contents of ndarray object can be accessed and modified by indexing or
slicing, just like Python's in-built container objects.
• Items in ndarray object follows zero-based index.

34
Numpy-Array- Indexing & Slicing
• A Python slice object is constructed by giving start, stop, and step parameters to
the built-in slice function.
• This slice object is passed to the array to extract a part of array.
from numpy import *
a=array([1,2,3,4,5,6])
s=slice(2,5,1)
print(a[s]) Output:
[3 4 5]

35
Numpy-Array- Indexing & Slicing
• The same result can also be obtained by giving the slicing parameters separated by a
colon : (start:stop:step) directly to the ndarray object.
from numpy import *
a=array([1,2,3,4,5,6]) Output:
s= a[2:5:1] [3 4 5]
print(s)
• If only one parameter is put, a single item corresponding to the index will be
returned.
from numpy import *
a=array([1,2,3,4,5,6]) Output:
s= a[5] 6
print(s)
36
Numpy-Array- Indexing & Slicing
• If a : is inserted in front of it, all items from that index onwards will be extracted.
from numpy import *
Output:
a=array([[1,2,3],[4,5,6],[7,8,9],[10,11,12]]) [[ 4 5 6]
print(a[1:]) [ 7 8 9]
[10 11 12]]
• If two parameters (with : between them) is used, items between the two indexes
(not including the stop index) with default step one are sliced.
from numpy import *
a=array([[1,2,3],[4,5,6],[7,8,9],[10,11,12]])
Output:
print(a[1:3]) [[4 5 6]
[7 8 9]]

37
• Slicing can also include ellipsis (…) to make a selection tuple of the same length as
the dimension of an array. If ellipsis is used at the row position, it will return an
ndarray comprising of items in rows. [[ 1 2 3] Output
from numpy import * [ 4 5 6]
a=array([[1,2,3],[4,5,6],[7,8,9],[10,11,12],[13,14,15]]) [ 7 8 9]
[10 11 12]
print(a) [13 14 15]]
print('Items in 2nd column are: ') Items in 2nd column are:
print(a[...,1]) [ 2 5 8 11 14]
print('Items in 2nd row are: ') Items in 2nd row are:
[4 5 6]
print(a[1,...]) Items in 2nd column onwards are:
print('Items in 2nd column onwards are: ') [[ 2 3]
print(a[...,1:]) [ 5 6]
print('Items in 2nd row onwards are: ') [ 8 9]
[11 12]
print(a[1:,...]) [14 15]]
Items in 2nd row onwards are:
[[ 4 5 6]
[ 7 8 9]
[10 11 12]
[13 14 15]] 38
Numpy Array Reshape
Reshaping means changing the shape of an array. The shape of
an array is the number of elements in each dimension. By
reshaping we can add or remove dimensions or change number
of elements in each dimension.

39
Example: Reshape From 1-D to 2-D
import numpy as np
arr = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12])
newarr = arr.reshape(4, 3)
print(newarr)

Output:
[[ 1 2 3]
[ 4 5 6]
[ 7 8 9]
[10 11 12]]

40
Example: Reshape From 1-D to 3-D
import numpy as np
arr = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12])
newarr = arr.reshape(2, 3, 2)
print(newarr)

Output:
[[[ 1 2]
[ 3 4]
[ 5 6]]
[[ 7 8]
[ 9 10]
[11 12]]]

41
Numpy Array Iterating
Iterating means going through elements one by one.
As we deal with multi-dimensional arrays in numpy, we can do
this using basic for loop of python.
If we iterate on a 1-D array it will go through each element one
by one.

42
Example: Iterate on the elements of the following 1-D array:
import numpy as np
arr = np.array([1, 2, 3])
for x in arr:
print(x)

Output:
1
2
3

43
Example: Iterate on the elements of the following 2-D array:
import numpy as np
arr = np.array([[1, 2, 3], [4, 5, 6]])
for x in arr:
print(x)
Output:
[1 2 3]
[4 5 6]

44
Example: Iterate on each scalar element of the 2-D array:
import numpy as np
arr = np.array([[1, 2, 3], [4, 5, 6]])
for x in arr:
for y in x:
print(y)
Output:
1
2
3
4
5
6

45
Example: Iterate on the elements of the following 3-D array:
import numpy as np
arr = np.array([[[1, 2, 3], [4, 5, 6]], [[7, 8, 9], [10, 11, 12]]])
for x in arr:
print(x)
Output:
[[1 2 3]
[4 5 6]]
[[ 7 8 9]
[10 11 12]]

46
Example: Iterate each element of 3D array
import numpy as np
arr = np.array([[[1, 2, 3], [4, 5, 6]], [[7, 8, 9], [10, 11, 12]]])
for x in arr:
for y in x:
for z in y:
print(z)
Output:
1
2
3
4
5
6
7
8
9
10
11
12

47
Numpy Array Join
Joining means putting contents of two or more arrays in a single
array.
In NumPy we join arrays by axes.
We pass a sequence of arrays that we want to join to the
concatenate() function, along with the axis. If axis is not explicitly
passed, it is taken as 0 (row-wise).

48
Example: Join two arrays (axis 0)
import numpy as np
arr1 = np.array([1, 2, 3])
arr2 = np.array([4, 5, 6])
arr = np.concatenate((arr1, arr2))
print(arr)
Output:
[1 2 3 4 5 6]

49
Example: Join two 2-D arrays along rows (axis=1):
import numpy as np
arr1 = np.array([[1, 2], [3, 4]])
arr2 = np.array([[5, 6], [7, 8]])
arr = np.concatenate((arr1, arr2), axis=1)
print(arr)
Output:
[[1 2 5 6]
[3 4 7 8]]

50
Numpy array split
Splitting is reverse operation of Joining.
Joining merges multiple arrays into one and Splitting breaks one
array into multiple.
We use array_split() for splitting arrays, we pass it the array we
want to split and the number of splits.

51
Example: Split the array in 3 parts:
import numpy as np
arr = np.array([1, 2, 3, 4, 5, 6])
newarr = np.array_split(arr, 3)
print(newarr)
Output:
[array([1, 2]), array([3, 4]), array([5, 6])]

Note: The return value is an array containing three arrays.

52
Example:If you split an array into 3 arrays, you can access them
from the result just like any array element:
import numpy as np
arr = np.array([1, 2, 3, 4, 5, 6])
newarr = np.array_split(arr, 3)
print(newarr[0])
print(newarr[1])
print(newarr[2])
Output:
[1 2]
[3 4]
[5 6]

53
Numpy Array search
You can search an array for a certain value, and return the
indexes that get a match.
To search an array, use the where() method.

54
Example: Find the indexes where the value is 4:
import numpy as np
arr = np.array([1, 2, 3, 4, 5, 4, 4])
x = np.where(arr == 4)
print(x)
Output:
array([3, 5, 6]

55
Example: Find the indexes where the values are even:
import numpy as np
arr = np.array([1, 2, 3, 4, 5, 6, 7, 8])
x = np.where(arr%2 == 0)
print(x)
Output:
array([1, 3, 5, 7]

56
Example: Find the indexes where the values are odd:
import numpy as np
arr = np.array([1, 2, 3, 4, 5, 6, 7, 8])
x = np.where(arr%2 == 1)
print(x)

Output:
array([0, 2, 4, 6])

57
Numpy Array Sort
Sorting means putting elements in an ordered sequence.
Ordered sequence is any sequence that has an order
corresponding to elements, like numeric or alphabetical,
ascending or descending.
The NumPy ndarray object has a function called sort(), that will
sort a specified array.

58
Example: Sort the array
import numpy as np
arr = np.array([3, 2, 0, 1])
print(np.sort(arr))

Output:
[0 1 2 3]

Note: This method returns a copy of the array, leaving the original array unchanged.

59
Example: Sort the array alphabetically.
import numpy as np
arr = np.array(['banana', 'cherry', 'apple'])
print(np.sort(arr))

Output:
['apple' 'banana' 'cherry']

60
Numpy Array Filter
Getting some elements out of an existing array and creating a
new array out of them is called filtering.
In NumPy, you filter an array using a boolean index list.
A boolean index list is a list of booleans corresponding to indexes
in the array.
If the value at an index is True that element is contained in the
filtered array, if the value at that index is False that element is
excluded from the filtered array.

61
Example: Create an array from the elements on index 0 and 2:
import numpy as np
arr = np.array([41, 42, 43, 44])
x = [True, False, True, False]
newarr = arr[x]
print(newarr)

Output:
[41 43]

62
Numpy-Random Number
• Numpy has sub module called random that is equipped with the
rand() function. Using this we can generate the random numbers
between 0 and 1.0.
random.rand()

• We can create a 1D array of random numbers by passing the size of


array to the rand() function as:
a=random.rand(n)

• We can create a 2D array of random numbers by passing the size of


array to the rand() function as:
a=random.rand(m,n)

63
Numpy-Random Number
import numpy.random
import numpy as np
print(np.random.rand())
print(np.random.rand(5))
print(np.random.rand(3,2))

64
Numpy-I/O
• The numpy.save() file stores the input array in a disk file
with npyextension.
from numpy import *
a=arange(8).reshape(4,2)
print(a)
save('outfile',a)

• To reconstruct array from outfile.npy, use load() function.


from numpy import *
b=load('outfile.npy')
print(b)

65
Numpy-I/O
• The storage and retrieval of array data in simple text file format is done with
savetxt() and loadtxt() functions.
from numpy import *
a=arange(8).reshape(4,2)
savetxt('out.txt',a)
b=loadtxt('out.txt')
print(b)

66
Numpy-Linear Algebra
• NumPy package contains numpy.linalg module that provides all the functionality
required for linear algebra. Some of the important function in this module are as
follows:
– dot(): To find the dot product of two arrays.
– vdot():To find the dot product of two vectors.
– inner(): To find the inner product of two arrays.
– matmul():To find the matrix product of two arrays.
– determinant(): To find the determinant of the array.
– inv(): find the multiplicative inverse of a matrix
– solve(): Solve the linear matrix equation

67

You might also like