You are on page 1of 10

CHAPTER – 4 – WORKING WITH NumPy

1. Introduction – NumPy is a module for Python. The name is an acronym for "Numeric Python" or "Numerical Python".
NumPy is not part of a basic Python installation. It has to be installed after the Python installation. NumPy enriches
the programming language Python with powerful data structures, implementing multi-dimensional arrays and
matrices. These data structures guarantee efficient calculations with matrices and arrays.
Array in general refers to a named group of homogeneous (of same type) elements. For example: Array of students
in each section, Array of ages of different people, Array of Names of different cities etc. NumPy arrays come in two
forms:
a. 1D (One dimensional) / Vectors - Single row array
Example – Array of age of eldest family member from each house in a society:
eldest_age_array[7]

position 0 1 2 3 4 5 6

45 85 65 25 38 63 42

To fetch any element we use its position. Such as: eldest_age_array[3] will result as 25
b. 2D (Two dimensional) – Also known as matrices / multidimensional array.
Example – Array of ages of all family members from each house in a society:
age_array[7][4]

position 0 1 2 3 4 5 6

0 45 15 65 48

1 13 16 62 53 44

2 56 62 12 13 45 18 21

3 25 28 39

To fetch any element we use its [row_position][column_position]. Such as: age_array[3][2] will
result as 39.
Elements in an array is stored in linear fashion as Row Major Implementation (First row -> Second row -> …) or
Column Major Implementation (First column -> Second column -> …)
2. A simple NumPy example:
Before we can use NumPy we will have to import it (Numpy is usually renamed to np) using below statement:
import numpy as np
Our first simple Numpy example deals with temperatures. Given is a list with values, e.g. temperatures in Celsius:
cvalues = [21.8, 21.2, 20.9, 20.1]
We will turn our list "cvalues" into a one-dimensional numpy array:
C = np.array (cvalues)
Print(C)
Let's assume, we want to turn the values into degrees Fahrenheit. This is very easy to accomplish with a numpy
array using below statement:
Print(C * 9 / 5 + 32)
Output - [71.24 70.16 69.62 68.18]
Note: The array C will not change by above calculation. So far, we referred to C as an array. The internal type is
"ndarray" or to be even more precise "C is an instance of the class numpy.ndarray". Which means that the arrays we
create using NumPy library are called ‘ndarray’.
3. Parts of NumPy Array (ndarray):
a. Axes – (Total no of dimension in an ndarray – 1) is
called its axes as axes are always numbers 0 onwards.
In figure, axis 0 runs along the rows, axis 1 runs along
the columns and axis 2 is assigned to the dimension
added after axis 0 and 1.
b. Rank – Total no of axes in an ndarray. In above
example it is 3.
c. Shape – It tells the number of elements along each axis of ndarray. In above example shape is (3, 4, 2) as
axis 0 has 3 rows, axis 1 has 4 columns and axis 3 has 2 size.
ndarray_var.shape
d. Datatype (dType) – It tells the type of data which is stored in ndarray. Default datatype of ndarray is float.
ndarray_var.dtype
e. ItemSize – It tells the size of each element of ndarray.
ndarray_var.itemsize
Example –
import numpy as np
val = [[5., 25., 45., 20.], [4., 23., 49., 17.], [6., 22., 47., 19.]]
x = np.array(val)
print('Size of ndarray is: ' + str(x.size))
print('Size of item is: ' + str(x.itemsize))
print('Shape of ndarray is: ' + str(x.shape))
print('Datatype of ndarray is: ' + str(x.dtype))
OUTPUT:

4. NumPy Arrays (ndarrays) v/s Python Lists: Elements in ndarrays and list can be saved and accessed in same
manner, however below are the key differences between both of them:
a. NumPy Arrays (ndarrays) are immutable while list is a mutable object.
b. NumPy Arrays (ndarrays) can store only similar kind of data while list can store different types of data in it.
c. NumPy Arrays (ndarrays) having same elements as a list occupy less storage, faster and convenient
compared to that list.
d. NumPy Arrays (ndarrays) support Vectorised Operations which means you can apply a function on all the
elements stored in an ndarray at once as shown above while converting temperature into Fahrenheit while
list does not support this feature.
5. NumPy Data Types:
a. bool_ - True/False
b. int_ (int8, int16, int32, int64) - Default datatype to store integer values
c. uint8, uint16, uint32, uint64 - Unsigned Integer values
d. float_(float16, float32, float64) - Default type to store decimal values
e. string_ - To store fixed length string data, for example:
To store string of 6 characters length datatype will
be S6
6. Creating One Dimensional NumPy Arrays (ndarrays):
a. Using array() –
import numpy as np
ary1 = np.array([2, 8.6, 6.8, 66])
The above statement will create an ndarray ‘ary1’ and store 4 elements in it. float_ datatype will be assigned
to ‘ary1’ as there are decimal elements also. To set the datatype manually below statement can be used:
import numpy as np
ary1 = np.array([2, 8.6, 6.8, 66], dtype = np.int64)
By assigning int64 datatype to this ndarray decimal values will lose the data as shown in below example:
Program –
import numpy as np
ary1 = np.array([2, 8.6, 6.8, 66], dtype = np.int64)
print(ary1.dtype)
print(ary1)
Output –

b. Using fromiter(): This method creates ndarrays from all types of sequences, such as: Numeric, Strings,
Dictionaries etc.
c. Using arange(): It is similar to range() function of Python, but it creates and ndarray instead of simple list. It
is pronounced as “a range” not “arrange”.
Syntax: <arrayname> = numpy.arange([start], [stop], [step], [dtype])
Program 1:
import numpy as np
nary1 = np.arange(1, 10, 1, np.int32)
print(nary1)
Output:
Program 2:
import numpy as np
nary1 = np.arange(1, 10, 0.5, np.float32)
print(nary1)
Output:
1. 1.5 2. 2.5 3. 3.5 4. 4.5 5. 5.5 6. 6.5 7. 7.5 8. 8.5 9. 9.5
d. Using linspace(): It creates ndarray and store evenly spaced elements between given limits (like
arithmetic progressions in mathematics).
Syntax: <arrayname> = numpy.linspace([start], [stop], [No of values])
Program 1:
import numpy as np
nary1 = np.linspace(1, 10, 5)
print(nary1)
Output:

Program 2:
import numpy as np
nary1 = np.linspace(2.2, 5.2, 4)
print(nary1)
Output:

7. Creating Two Dimensional NumPy Arrays (ndarrays):


a. Using array():
import numpy as np
ary1 = np.array([2, 8.6, 6.8, 66], [25, 36, 33])
The above statement will create a two dimensional ndarray ‘ary1’ and store 7 elements in it. float_ datatype
will be assigned to ‘ary1’ as there are decimal elements also.
b. Using arange(): It can only create one dimensional ndarrays, however those elements of those ndarrays
can be stored/re-assigned into multiple rows/columns as per the requirement as shown below:
import numpy as np
ary = np.arange(1, 11, 1) //will produce elements from 1 to 10
and store in ary1
ary1 = ary.reshape(5, 2) //will store all the elements in five
rows two columns as shown below
1 2
3 4
5 6
7 8
9 10
ary2 = ary.reshape(2, 5) //will store all the elements in two
rows five columns as shown below

1 2 3 4 5
6 7 8 9 10
8. Some alternative ways to create One and Two Dimensional NumPy Arrays (ndarrays):
a. Using empty(): It creates empty 1-D or 2-D ndarray of any shape, user can store elements later.
Syntax – numpy.empty([row/s, column/s], dtype)
Program 1 - import numpy as np
arry = np.empty([5, 2])
print(arry)
empty_like(existed_array) method can be used to create an empty existing array shape ndarray.
b. Using zeros(): It creates 1-D or 2-D ndarray of any shape filled with 0s as elements.
Syntax – numpy.zeros([row/s, column/s], dtype)
Program 1 - import numpy as np
arry = np.zeros([5, 6], np.int32)
print(arry)
Output –

zeros_like(existed_array) method can be used to create an existing array shape ndarray filled with zeros.
c. Using ones(): It creates 1-D or 2-D ndarray of any shape filled with 1s as elements.
Syntax – numpy.ones([row/s, column/s], dtype)
Program 1 - import numpy as np
arry = np.ones([4, 3], np.int32)
print(arry)
Output –

zeros_like(existed_array) method can be used to create an existing array shape ndarray filled with ones.
d. Using eye(): It creates identity matrix ndarray (0s at non-diagonal positions and 1s at diagonal positions).
These ndarray must have equal number of rows and columns.
Syntax – numpy.eye(size)
Program 1 - import numpy as np
arry = np.eye(6)
print(arry)
Output –

e. Using full(): It creates 1-D or 2-D ndarray filled with provided element like zeros or ones.
Syntax – numpy.full((no of rows, no of columns), element to fill)
Program 1 - import numpy as np
arry = np.full((5, 8), 7)
print(arry)
Output –

f. Using random.rand(): It creates 1-D or 1-D ndarray filled with random floating values in range 0 to 1.
Syntax – numpy.random.rand(no of rows, no of columns)
Program 1 - import numpy as np
arry = np.random.rand(2, 3)
print(arry)
Output –

Program 2 - import numpy as np


arry = np.random.rand(2, 3) * 100 // Range 0 - 100
print(arry)
Output –

g. Using random.randint(): It creates 1-D or 1-D ndarray filled with random integer values in range given.
Syntax – numpy.random.randint(range_till, size=(rows, columns))
Program 1 - import numpy as np
arry = np.random.randint(8, size=(5, 4))
//Above statement will fill the ndarray with random numbers between 0 to 7
print(arry)
Output –
9. Working with NumPy arrays:
a. Accessing individual elements: To access an element using its index/position.
For 1-D ndarray:
arry = np.array([5, 8, 7, 9]) //This statement will produce below illustrated ndarray
+INDEXES/POSITIONS 0 1 2 3
ELEMENTS 5 8 7 9
-INDEXES/POSITIONS -4 -3 -2 -1
In above ndarray arry:
i) print(arry[3]) //Output - 9. ii) print(arry[-3]) //Output – 8.
For 2-D ndarray:
arry = np.array(([5, 6, 8], [9, 3, 2], [11, 42, 32])) //This statement will produce below illustrated ndarray
+INDEXES/POSITIONS 0 1 2
0 5 6 8 -3
1 9 3 2 -2
2 11 42 32 -1
-3 -2 -1 -INDEXES/POSITIONS
In above ndarray arry:
i) print(arry[1][2]) //Output – 2
ii) print(arry[-2][-3]) //Output – 9
iii) print(arry[-1][1]) //Output – 42
b. NumPy ndarray slices: Slices extract a part/subset from an existing ndarray.
Syntax - <ndarry_name>[Start : Stop : Step]
When Start or Stop or Step values are not mentioned their default values are considered as:
Start = 0; Stop = Dimension Size; Step = 1
For example –
*For 1-D ndarray ‘arry’ created in 9.a
Syntax - <ndarry_name>[Start : Stop : Step]
arry[1:3] //Extract new ndarray starting from position 1 to 2 as [8, 7]
arry[-2:-4] //Extract new ndarray without any elements because -2 is greater than -4 and
reverse slicing is not possible
arry[-2:-1] //Extract new ndarray starting from position -2 to -2 as [7]
*For 2-D ndarray ‘arry’ created in 9.a
Syntax - <ndarry_name>[Rows <Start : Stop : Step>,
Columns <Start : Stop : Step>]
arry[1:2, 2:3] //Extract new ndarray with rows starting from 1 to 1 and columns 2 to 2 as [[2]]
c. Splitting NumPy ndarrays: Split functions are another ways to extract part/subset from an ndarray.
Syntax: numpy.split(<ndarray>, <n>)
i. Using hsplit(): It extracts ndarray horizontally in equal subparts.
ii. Using vsplit(): It extracts ndarray vertically in equal subparts.
iii. Using split(): It is a general function which can be used to extract along axis 0 or 1.
Example – import numpy as np
ary = np.arange(24.0).reshape(4, 6)
print(np.hsplit(ary, 2)) //output1
print(np.hsplit(ary, 3)) //output2
print(np.vsplit(ary, 2)) //output3
print(np.hsplit(ary, 4)) //output4
output1 output2

output3

output4
ValueError: array split does not result in an equal division
d. Joining NumPy ndarrays: 1-D or 2-D ndarrays in Python can be combined / joined vertically using
vstack() or horizontally hstack().
Syntax – numpy.vstack((ndarray1, ndarray2, ndarray3, ……))
numpy.vstack((ndarray1, ndarray2, ndarray3, ……))
Program 1 – import numpy as np
arry1 = np.array(([5, 6, 8], [9, 3, 2]))
arry2 = np.array(([1, 2, 3], [11, 42, 32]))
print(np.vstack((arry1, arry2)))
Output –

Program 2 - import numpy as np


arry1 = np.array(([5, 6, 8], [9, 3, 2]))
arry2 = np.array(([1, 2, 3], [11, 42, 32]))
print(np.hstack((arry1, arry2)))
Output –

e. Concatenating NumPy ndarrays: Concatenate function can be used to join ndarrays along axes like axis
0 (rows) or axis 1 (column).
Syntax – numpy.concatenate(ndarrays, [axis=<0 or 1>])
If axis is not passed in concatenate function, by default axis 0 is considered.
*If axis is 0, then column dimension of all ndarrays must match
* If axis is 1, then row dimension of all ndarrays must match
Program 1 – import numpy as np
arry1 = np.array(([5, 6, 8], [9, 3, 2]))
arry2 = np.array(([1, 2, 3], [11, 42, 32]))
print(np.concatenate((arry1, arry2), axis=0))
Output –

Program 2 – import numpy as np


arry1 = np.array(([5, 6, 8], [9, 3, 2]))
arry2 = np.array(([1, 2, 3], [11, 42, 32]))
print(np.concatenate((arry1, arry2), axis=1))
Output –

f. Extracting Condition based Subsets: There are various built-in functions available which can be applied
on existed ndarrays to extract new ndarrays based on some condition/calculation.
Syntax – numpy.extract(<condition>, <array>)
Example –
import numpy as np
ary = np.arange(1, 13, 1)
print("Created ndarray using arange is -")
print(ary)
ary1 = ary.reshape(3, 4)
print("\nReshaped ndarray is -")
print(ary1)
cond = np.mod(ary, 2)==0
print("\nndarray after applying condition is -")
print(cond)
print("\nExtracted ndarray is -")
print(np.extract(cond, ary1))
Output –

Various important functions of ndarray are:


floor(x), ceil(x), add(x, <n>), multiply(x, <n>), divide(x, <n>),
power(x, <n>), subtract(x, <n>), mod(x, <n>), remainder(x, <n>),
sqrt(x), cbrt(x), square(x)

Operators which can be applied on ndarrays:


+ (Addition), - (Subtraction), * (Multiplication), / (Division)
and % (Modulus)

You might also like