Lab 2, Python Numpy - LUMS
Lab 2, Python Numpy - LUMS
NumPy or Numerical Python is a Python library used for working with arrays. It also has functions
for working in domain of linear algebra and matrices. NumPy was created in 2005 by Travis
Oliphant. It is an open source project and you can use it freely. In Python we have lists that serve
the purpose of arrays, but they are slow to process. NumPy aims to provide an array object that is
up to 50x faster than traditional Python lists.
The array object in NumPy is called ndarray, it provides a lot of supporting functions that make
working with ndarray very easy. Arrays are very frequently used in data science, where speed and
resources are very important.
Features
Multidimensional arrays
Slicing/indexing
Math and logic operations
Applications
Computation with vectors and matrices
Provides fundamental Python objects for data science algorithms
array is the main object provided by NumPy
Characteristics
Fixed Type
All its elements have the same type
Multidimensional
Allows representing vectors, matrices and n dimensional arrays
NumPy advantages:
Higher flexibility of indexing methods and operations
Higher efficiency of operations
Note: Remember that unlike Python lists, NumPy is constrained to arrays that all contain the same type.
If types do not match, NumPy will upcast if possible (here, integers are upcast to floating point):
By: Faizan Irshad Page 2
Introduction to NumPy Library
Indexing of arrays
Getting and setting the value of individual array elements
Slicing of arrays
Getting and setting smaller subarrays within a larger array
Reshaping of arrays
Changing the shape of a given array
Moreover, let’s start by defining three random arrays: a one-dimensional, two-dimensional, and
three-dimensional array. We’ll use NumPy’s random number generator:
import numpy as np
x1 = np.random.randint(10, size=5) # One-dimensional array
x2 = np.random.randint(10, size=(3, 4)) # Two-dimensional array of size 3 by 4
x3 = (np.random.randint(10, size=(3, 4, 5)) # Three-dimensional array of size 4 by 5
The NumPy slicing syntax follows that of the standard Python list; to access a slice of
an array x, use this:
x[start:stop:step]
In case any of these are unspecified, they default to the values start=0, stop=size of dimension,
step=1. We’ll take a look at accessing subarrays in one dimension and in multiple dimensions.
x1 = np.random.randint(10, size=5)
print(x1)
A potentially confusing case is when the step value is negative. In this case, the defaults for start
and stop are swapped. This becomes a convenient way to reverse an array:
print(x1[::-1])
Multidimensional arrays
x2 = np.random.randint(10, size=(3, 4))
x2[:2, :3] # two rows (0, 1), three columns (0, 1, 2)
x2[:3, ::2] # all rows, every other column