You are on page 1of 18

Introduction to Numpy

Numpy : Package in Python


 NumPy stands for ‘Numerical Python’. It is a package for data analysis
and scientific computing with Python.
 NumPy arrays facilitate advanced mathematical and other types of
operations on large numbers of data.
 NumPy is not another programming language but a Python extension
module.
 The powerful n-dimensional array in NumPy speeds-up data
processing.
Installing NumPy

 Open CMD, Execute the following command.


pip install NumPy

Importing NumPy

 Open Python IDLE, execute the following command:


import numpy #or
import numpy as np
2
Important Points about Array
 We can create a N-dimensional array in python using numpy.array().

 Array are by default Homogeneous, which means data inside an array


must be of the same Datatype.

 Element wise operation is possible.

 Numpy array has the various function, methods, and variables, to ease
our task of matrix computation.
 Elements of an array are stored contiguously in memory. 3
1-D , 2-D or N-D Numpy Arrays

4
NumPy Arrays Vs Lists

5
Benefits of NumPy Array over
Lists
 1) Numpy Arrays consumes less memory as compared to Lists.
In this example, a Python list and a Numpy array of size 1000 will be created. The
size of each element and then the whole size of both the containers will be
calculated and comparison will be done in terms of memory consumption.
import numpy as np
import sys
  
# declaring a list of 1000 elements 
S= range(1000)
  
# printing size of each element of the list
print("Size of each element of list in bytes: ",sys.getsizeof(S))
  
print("Size of the whole list in bytes: ",sys.getsizeof(S)*len(S))
  
# declaring a Numpy array of 1000 elements 
D= np.arange(1000)
  
print("Size of each element of the Numpy array in bytes: ",D.itemsize)
  
print("Size of the whole Numpy array in bytes: ",D.size*D.itemsize)
6
Benefits of NumPy Array over
Lists
 2) Numpy Arrays are fast as compared to Python Lists.
In this example, 2 Python lists and 2 Numpy arrays are created, and each container has
1000000 elements. Multiplication of elements in both the lists and Numpy arrays
respectively is carried out and the difference in time needed for the execution for both
the containers is analyzed to determine which one takes less time to perform the
operation.
import numpy
import time

size = 1000000  
list1 = range(size)
list2 = range(size)
array1 = numpy.arange(size)  
array2 = numpy.arange(size)
   
# capturing time before the multiplication of Python lists
initialTime = time.time()
  
# multiplying  elements of both the lists and stored in another list
resultantList = [(a * b) for a, b in zip(list1, list2)]
7
Benefits of NumPy Array over
Lists
 Example Continue...

# calculating execution time


print("Time taken by Lists to perform multiplication:", 
      (time.time() - initialTime),
      "seconds")
   
# capturing time before the multiplication of Numpy arrays
initialTime = time.time()
  
# multiplying  elements of both the Numpy arrays
resultantArray = array1 * array2
   
# calculating execution time 
print("Time taken by NumPy Arrays to perform multiplication:",
      (time.time() - initialTime),
      "seconds")

8
Benefits of NumPy Array over
Lists
 3) Numpy Arrays support element-wise operations, Lists don’t.
In this example, the incapability
import numpy as np of the Python list to carry out a basic operation is
demonstrated. A Pythona list
# declaring listand a Numpy array having the same elements will be
declaredlsand=[1,
an integer
2, 3]will be added to increment each element of the container by that
integer value
arr without looping statements. The effect of this operation on the Numpy array
= np.array(ls)
and Python list will be analyzed.
try:
    # adding 4 to each element of list
    ls = ls + 4   
except(TypeError):
    print("Lists don't support list + int")

# now on array
try:
    # adding 4 to each element of Numpy array
    arr = arr + 4
    print("Modified Numpy array: ",arr)  
except(TypeError):
    print("Numpy arrays don't support list + int") 9
NumPy Array Creation Routines
 Numpy arrays can be created in different ways:
1. By using numpy.empty() function : The empty routine is used to
create an uninitialized array of specified shape and data type.
Syntax:
numpy.empty(shape, dtype = float, order = 'C')  
• Shape: The desired shape of the specified array.
• dtype: The data type of the array items. The default is the float.
• Order: The default order is the c-style row-major order. It can be set to
F for FORTRAN-style column-major order.

10
NumPy Array Creation Routines
2. By using numpy.zeros() function : This routine is used to create the
numpy array with the specified shape where each numpy array item is
initialized to 0.
Syntax:
numpy.zeros(shape, dtype = float, order = 'C')  

11
NumPy Array Creation Routines
3. By using numpy.ones() function : This routine is used to create the
numpy array with the specified shape where each numpy array item is
initialized to 1.
Syntax:
numpy.ones(shape, dtype = float, order = 'C')  

12
NumPy Array Creation Routines
4. By using numpy.full() function : This routine is used to create the
numpy array with the specified shape where each numpy array item is
initialized to 1.
Syntax:
numpy.full(shape, fill_value, dtype = None, order = ‘C’) 

13
NumPy Array Creation Routines
5. By using numpy.arange() function : This routine is used to create one
dimensional numpy array with specified start, end and step values.
Syntax:
numpy.arrange([start,] stop[, step,][, dtype])

 The advantage of numpy.arange() over the normal in-built range()


function is that it allows us to generate sequences of numbers that are
not integers. 14
Arrays from Existing Data
 NumPy also provides us the way to create an array by using the existing data.

1. numpy.asarray() Function :
 This routine is used to create an array by using the existing data in the
form of lists, or tuples.
 This routine is useful in the scenario where we need to convert a python
sequence into the numpy array object.
 Syntax:
numpy.asarray(sequence,  dtype = None, order = None)  
sequence: Input data in any form such as list, list of tuples, tuples, tuple of
tuples or tuple of lists
dtype: By default, the data type of input data is applied to the resultant
ndarray
order: (row major) or F (column major). C is default
15
Arrays from Existing Data
numpy.asarray() Examples :
1 2 3

16
Arrays from Existing Data
Difference in numpy.array() and numpy.as array():

 The vital difference between the above two methods is that


numpy.array() will make a duplicate of the original object and
numpy.asarray() would mirror the changes in the original object. i.e :

 When a copy of the array is made by using numpy.asarray(), the changes


made in one array would be reflected in the other array also but doesn’t
show the changes in the list by which if the array is made. However, this
doesn’t happen with numpy.array().

17
Arrays from Existing Data
Example : import numpy as np
lst = [1, 7, 0, 6, 2, 5, 6]
# converting list to array
arr = np.asarray(lst)

print ("List:", lst)


print ("arr: ", arr)
 
# made another array out of arr using asarray function
arr1 = numpy.asarray(arr)
 
#displaying arr1 before the changes made
print("arr1: " , arr1)
 
#change made in arr1
arr1[3] = 23
 
#displaying arr1 , arr , list after the change has been made
print("lst: " , lst)
print("arr: " , arr)
print("arr1: " , arr1)
18

You might also like