0% found this document useful (0 votes)
5 views

11.1 NumPy

NumPy, short for Numerical Python, is a library for data analysis and scientific computing in Python, primarily utilizing arrays to store multiple values. It provides various built-in functions for creating, manipulating, and transforming these arrays, including 1-D and 2-D arrays. The document also covers array indexing, slicing, and methods to determine dimensions and shapes of arrays.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views

11.1 NumPy

NumPy, short for Numerical Python, is a library for data analysis and scientific computing in Python, primarily utilizing arrays to store multiple values. It provides various built-in functions for creating, manipulating, and transforming these arrays, including 1-D and 2-D arrays. The document also covers array indexing, slicing, and methods to determine dimensions and shapes of arrays.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 17

11/17/23, 12:04 PM 11.

1 NumPy

11.1 Numerical Python (NumPy)


NumPy stands for ‘Numerical Python’.

It is a library for data analysis and scientific computing with Python.

Numpy is used with a special datatype 'Array'.

An array is a data type used to store multiple values/elements using a single identifier
(variable name).

Consider an array with 5 numbers: [ 10, 9, 99, 71, 90 ]

The first element has a value of '10' and is at index position [0]

NumPy arrays (also called ndarray) are used to store lists of numerical data, vectors and
matrices.

The NumPy library has a large set of routines (built-in functions) for creating,
manipulating,and transforming NumPy arrays.

11.2 Difference Between List and Array

11.3 Creation of NumPy Arrays from List

a). Creating a 1-D Array


An array with only single row of elements is called 1-D array

file:///C:/Users/USER/Documents/JOHN/Documents/EBE309/Numpy/11.1 NumPy.html 1/17


11/17/23, 12:04 PM 11.1 NumPy

In [5]: #import NumPy library


import numpy as np

#Create a list
lst=[10,15,20,25.1]

#Create 1-D NumPy Array


arr1=np.array(lst)

#Display the contents of the array


arr1

array([10. , 15. , 20. , 25.1])


Out[5]:

In [3]: type(arr1)

numpy.ndarray
Out[3]:

In [ ]: np.shape(arr1)

In [6]: # string datatype '<U11'

arr1.dtype

dtype('float64')
Out[6]:

In [7]: new_arr=np.array([11.0,22,33,44,55])
new_arr

array([11., 22., 33., 44., 55.])


Out[7]:

In [ ]: new_arr.dtype

In [ ]: # 1-D array

arr1.ndim

Notice in the cell above, all intergers have been converted to a string datatype '

This is because the occurance of a single string in the list 'lst' makes the whole
array to be converted to string datatype

b). Creating a 2-D Array (Matrix)


An array with only multiple rows of elements is called a 2-D array.

file:///C:/Users/USER/Documents/JOHN/Documents/EBE309/Numpy/11.1 NumPy.html 2/17


11/17/23, 12:04 PM 11.1 NumPy

In [8]: #Create lists


lst1=[10,15,20,25]
lst2=[1.1,2.2,3.3,4.4]
lst3=[100,200,300,400]

#Create 2-D NumPy Array


arr2=np.array([lst1,lst2,lst3])

#or (another method of doing the same thing)

arr2=np.array([[10,15,20,25],[1.1,2.2,3.3,4.4],[100,200,300,400]])

#Display the contents of the array


arr2

array([[ 10. , 15. , 20. , 25. ],


Out[8]:
[ 1.1, 2.2, 3.3, 4.4],
[100. , 200. , 300. , 400. ]])

In the cell above, notice the intergers have been converted to floats we can test
the datatype in the cell below to confirm this ...

In [9]: arr2.dtype

file:///C:/Users/USER/Documents/JOHN/Documents/EBE309/Numpy/11.1 NumPy.html 3/17


11/17/23, 12:04 PM 11.1 NumPy
dtype('float64')
Out[9]:

In [10]: # 2-D array

arr2.ndim

2
Out[10]:

In [11]: np.shape(arr2)

(3, 4)
Out[11]:

We can force the array creating to take a specific datatype as follows...

In [12]: #float

arr3 = np.array([[1,2],[3,4]],dtype=float)
arr3.dtype

dtype('float64')
Out[12]:

In [14]: #integer
arr3=np.array([[1.1,2.0],[3.3,4.7]],dtype=int)
arr3.dtype
arr3

array([[1, 2],
Out[14]:
[3, 4]])

In [15]: #string
arr3=np.array([[1.1,2.0],[3.3,4.7]],dtype=str)
arr3.dtype

dtype('<U3')
Out[15]:

In [16]: np.shape(arr3)

(2, 2)
Out[16]:

c).Other ndarray creation methods


In [18]: # 3 by 4 array containing only zeros
# datatype is automatically float

arr=np.zeros((5,1),dtype=int) # vector
arr

array([[0],
Out[18]:
[0],
[0],
[0],
[0]])

In [19]: # 2 by 5 array containing only ones

arr=np.ones((6,1)) # vector
arr

file:///C:/Users/USER/Documents/JOHN/Documents/EBE309/Numpy/11.1 NumPy.html 4/17


11/17/23, 12:04 PM 11.1 NumPy
array([[1.],
Out[19]:
[1.],
[1.],
[1.],
[1.],
[1.]])

In [ ]:

In [20]: # an array with numbers in a given range and sequence using the arange() function
# 0 to 5
# 1-D array

arr=np.arange(11)
arr

array([ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10])
Out[20]:

In [21]: # stepping
# 3steps
# 1-D array

arr=np.arange(-2,10,3)
arr

array([-2, 1, 4, 7])
Out[21]:

In [22]: # negative stepping (reversed array)


# - 3 steps
# 1-D array

arr=np.arange(15,2,-3)
arr

array([15, 12, 9, 6, 3])


Out[22]:

In [23]: # identity matrix

arr_ident=np.eye(5)
arr_ident

array([[1., 0., 0., 0., 0.],


Out[23]:
[0., 1., 0., 0., 0.],
[0., 0., 1., 0., 0.],
[0., 0., 0., 1., 0.],
[0., 0., 0., 0., 1.]])

11.4 Ndarray methods

a). Finding the dimensions of an array (NB: Arrays


can be 1-D, 2-D or n-D.)</b>

NumPy calls the dimensions as axes (plural of axis). Thus, a 2-D array has two
axes.

The row-axis is called axis 0 and the column-axis is called axis 1.


file:///C:/Users/USER/Documents/JOHN/Documents/EBE309/Numpy/11.1 NumPy.html 5/17
11/17/23, 12:04 PM 11.1 NumPy

In [24]: #dimensions
arr1=np.array([5,6,7])
arr2=np.array([[10,15,20,25],[1.1,2.2,3.3,4.4],[100,200,300,400]])

#ndim method
arr1.ndim # dimensions = 1
arr2.ndim # dimensions = 2

print(str(arr1.ndim) +', '+ str(arr2.ndim))

1, 2

b). Finding the size of the array for each dimension


(also known as the 'Shape of the array')
In [25]: #shape method

arr1=np.array([5,6,7])
arr2=np.array([[10,15,20,25],[1.1,2.2,3.3,4.4],[100,200,300,400]])

In [26]: # 1-D array

arr1.shape

(3,)
Out[26]:

In [27]: arr2.shape

(3, 4)
Out[27]:

In [ ]: # 2-D array (vector)

arr3=np.ones((5,1))
arr3.shape

In [ ]: # 2-D array (matrix)

arr2.shape

c). Finding the number of elements in a ndarray


In [28]: #size method

arr1=np.array([11,12])
arr2=np.array([5,6,7])
arr3=np.array([[10,15,20,25],[1.1,2.2,3.3,4.4],[100,200,300,400]])

In [29]: arr1.size

2
Out[29]:

In [30]: arr2.size

3
Out[30]:

file:///C:/Users/USER/Documents/JOHN/Documents/EBE309/Numpy/11.1 NumPy.html 6/17


11/17/23, 12:04 PM 11.1 NumPy

In [31]: arr3.size

12
Out[31]:

11.5 Array Indexing and Slicing

a). Indexing

Indexing 1-D array


In [32]: arr=np.array([10,15,20,25,45])
arr

array([10, 15, 20, 25, 45])


Out[32]:

In [33]: # Index of '10'

arr[0] #index 0

10
Out[33]:

In [34]: # Index of '20'

arr[2] #index 2

20
Out[34]:

In [35]: # Index location of '45'

arr[4] #index 4

45
Out[35]:

Indexing 2-D array

For 2-D arrays indexing for both dimensions starts from 0.

Each element is referenced through two indexes i and j, where i represents the row
number and j represents the column number.

Example: Consider the following 2-D array consisting of student marks; create an
array called marks to store marks given in three subjects for four students given in
this table.

file:///C:/Users/USER/Documents/JOHN/Documents/EBE309/Numpy/11.1 NumPy.html 7/17


11/17/23, 12:04 PM 11.1 NumPy

In [36]: #create the array

marks=np.array([[78,67,56],[76,75,47],[84,59,60],[67,72,54]])
marks

array([[78, 67, 56],


Out[36]:
[76, 75, 47],
[84, 59, 60],
[67, 72, 54]])

There are 4 students (i.e. 4 rows) and 3 subjects (i.e. 3 columns), the array will be
called marks[4][3].

This array can store 4*3 = 12 elements.

Here, marks[i,j] refers to the element at (i+1)th row and (j+1)th column because
the index values start at 0.

In [37]: #Get 'Science marks' for 'Harun'

marks[2][2]

60
Out[37]:

In [38]: #Get 'Maths marks' for 'Vedika'

marks[1][0]

76
Out[38]:

In [ ]: #Get 'English marks' for 'Prasad'

marks[3][1]

b). Slicing
Sometimes we need to extract part of an array.

This is done through slicing.

We can define which part of the array to be sliced by specifying the start and end
index values using [start : end] along with the array name.

file:///C:/Users/USER/Documents/JOHN/Documents/EBE309/Numpy/11.1 NumPy.html 8/17


11/17/23, 12:04 PM 11.1 NumPy

Slicing 1-D array


In [39]: arr=np.array([-2, 2, 6, 10, 14, 18, 22])
arr

array([-2, 2, 6, 10, 14, 18, 22])


Out[39]:

In [40]: # Get -2 to 6 exclusive


arr[0:2]

array([-2, 2])
Out[40]:

In [41]: # Get -2 to 6 inclusive


arr[0:3]

array([-2, 2, 6])
Out[41]:

In [44]: arr[3:]

array([10, 14, 18, 22])


Out[44]:

In [45]: # reverse the array


arr[::-1]

array([22, 18, 14, 10, 6, 2, -2])


Out[45]:

Slicing 2-D array


In [46]: #create 2-D array

arr=np.array([[ -7, 0, 10, 20],[ -5, 1, 40, 200],[ -1, 1, 4, 30]])


arr

array([[ -7, 0, 10, 20],


Out[46]:
[ -5, 1, 40, 200],
[ -1, 1, 4, 30]])

In [47]: # Get first 2 elements of the last row

arr[2:,0:2]

array([[-1, 1]])
Out[47]:

In [48]: arr

array([[ -7, 0, 10, 20],


Out[48]:
[ -5, 1, 40, 200],
[ -1, 1, 4, 30]])

In [ ]: # method 1
# access all the elements in the 3rd column
# access all rows (i.e. row index 1 to row index 2 - inclusive)
# access index 2 (NOTE: this is not a range therefore index is specific to the elem

arr[0:3,2]

file:///C:/Users/USER/Documents/JOHN/Documents/EBE309/Numpy/11.1 NumPy.html 9/17


11/17/23, 12:04 PM 11.1 NumPy

In [ ]: # method 2
# access all the elements in the 3rd column
# access all rows (i.e. row index 1 to row index 2 - inclusive)
# access index 2 (NOTE: this is not a range therefore index is specific to the elem

arr[:,2]

In [ ]: # access elements of 2nd and 3rd row from 1st and 2nd column
# method 1

arr[1:3,0:2]

In [ ]: # access elements of 2nd and 3rd row from 1st and 2nd column
# method 2

arr[1:,:2]

In [ ]: # access elements of 1st and 2nd row from 3rd and 4th column
# method 1

arr[0:2,2:4]

In [ ]: # access elements of 1st and 2nd row from 3rd and 4th column
# method 2

arr[:2,2:4]

If row indices are not specified, it means all the rows are to be considered.

In [ ]: #access all rows of column 2


arr[:,2]

Likewise, if column indices are not specified, all the columns are to be considered.

In [ ]: #access all columns of row 2


arr[1,:]

11.6 Operations on Arrays

a). Arithmetic Operations


When we perform a basic arithmetic operation like addition, subtraction,
multiplication, division etc. on two arrays, the operation is done on each
corresponding pair of elements.

For instance, adding two arrays will result in the first element in the first array to
be added to the first element in the second array, and so on.

This is called 'Elementwise operations.'

Elementwise operations require both arrays to have the same shape.

file:///C:/Users/USER/Documents/JOHN/Documents/EBE309/Numpy/11.1 NumPy.html 10/17


11/17/23, 12:04 PM 11.1 NumPy

In [49]: arr1 = np.array([[3,6],[4,2]])


arr2 = np.array([[10,20],[15,12]])

arr1.shape==arr2.shape

True
Out[49]:

In [50]: arr1

array([[3, 6],
Out[50]:
[4, 2]])

In [51]: arr2

array([[10, 20],
Out[51]:
[15, 12]])

In [52]: # Element-wise addition of two matrices

arr1+arr2

array([[13, 26],
Out[52]:
[19, 14]])

In [53]: # Element-wise subtraction of two matrices

arr1-arr2

array([[ -7, -14],


Out[53]:
[-11, -10]])

In [ ]: # Element-wise multiplication of two matrices

arr1*arr2

In [54]: # Element-wise division of two matrices

arr1/arr2

array([[0.3 , 0.3 ],
Out[54]:
[0.26666667, 0.16666667]])

In [55]: # Element-wise exponention of two matrices

arr1**arr2

array([[ 59049, -1190133760],


Out[55]:
[ 1073741824, 4096]])

In [56]: # Exponention with an integer/float

arr1**3.5

array([[ 46.7653718 , 529.08978444],


Out[56]:
[128. , 11.3137085 ]])

In [57]: # Element wise Remainder of Division


# (Modulo)

arr2 % arr1

array([[1, 2],
Out[57]:
[3, 0]])

file:///C:/Users/USER/Documents/JOHN/Documents/EBE309/Numpy/11.1 NumPy.html 11/17


11/17/23, 12:04 PM 11.1 NumPy

b). Transposition
Transposing an array turns its rows into columns and columns into rows just like
matrices in mathematics.

In [58]: # Create array

arr = np.array([[10,-7,0, 20],[-5,1,200,40],[30,1,-1,4]])


arr

array([[ 10, -7, 0, 20],


Out[58]:
[ -5, 1, 200, 40],
[ 30, 1, -1, 4]])

In [59]: # Transpose the array

arr.transpose()

array([[ 10, -5, 30],


Out[59]:
[ -7, 1, 1],
[ 0, 200, -1],
[ 20, 40, 4]])

c). Sorting
Sorting is to arrange the elements of an array in hierarchical order either
ascending or descending.

By default, numpy does sorting in ascending order.

In [60]: # create 1-D array

arr = np.array([1,0,2,-3,6,8,4,7])
arr

array([ 1, 0, 2, -3, 6, 8, 4, 7])


Out[60]:

In [61]: # Sort 1-D array

arr.sort()
arr

array([-3, 0, 1, 2, 4, 6, 7, 8])
Out[61]:

Sorting 2-D array

In 2-D array, sorting can be done along either of the axes i.e., row-wise or column-
wise.

By default, sorting is done per row (i.e., on axis = 1). It means to arrange elements
in each row in ascending order.

file:///C:/Users/USER/Documents/JOHN/Documents/EBE309/Numpy/11.1 NumPy.html 12/17


11/17/23, 12:04 PM 11.1 NumPy

When axis=0, sorting is done per column, which means each column is sorted in
ascending order.

In [62]: # create 2-D array

arr1=np.array([[10,-7,0, 20],[-5,1,200,40],[30,1,-1,4]])
arr2=np.array([[10,-7,0, 20],[-5,1,200,40],[30,1,-1,4]])
arr3=np.array([[10,-7,0, 20],[-5,1,200,40],[30,1,-1,4]])

arr1

array([[ 10, -7, 0, 20],


Out[62]:
[ -5, 1, 200, 40],
[ 30, 1, -1, 4]])

In [63]: # Default sorting (per row)

arr1.sort() # implicit that axis=1


arr1

array([[ -7, 0, 10, 20],


Out[63]:
[ -5, 1, 40, 200],
[ -1, 1, 4, 30]])

In [64]: arr2

array([[ 10, -7, 0, 20],


Out[64]:
[ -5, 1, 200, 40],
[ 30, 1, -1, 4]])

In [65]: # Sort explicitly per row


# NOTE:axis = 1 refers to columns

arr2.sort(axis=1)
arr2

array([[ -7, 0, 10, 20],


Out[65]:
[ -5, 1, 40, 200],
[ -1, 1, 4, 30]])

In [66]: arr3

array([[ 10, -7, 0, 20],


Out[66]:
[ -5, 1, 200, 40],
[ 30, 1, -1, 4]])

In [67]: # Sort explicitly per column


# NOTE:axis = 0 refers to rows

arr3.sort(axis=0)
arr3

array([[ -5, -7, -1, 4],


Out[67]:
[ 10, 1, 0, 20],
[ 30, 1, 200, 40]])

d). Concatenation

file:///C:/Users/USER/Documents/JOHN/Documents/EBE309/Numpy/11.1 NumPy.html 13/17


11/17/23, 12:04 PM 11.1 NumPy

Concatenation means joining two or more arrays.

Concatenating 1-D arrays means appending the sequences one after another.

In [74]: arr1=np.zeros(3)
arr2=np.ones(3)

arr1

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


Out[74]:

In [69]: arr2

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


Out[69]:

In [70]: # concatenate 1-D arrays rowwise

arr3=np.concatenate((arr1,arr2)) # concatenate on the same row


arr3

array([0., 0., 0., 1., 1., 1.])


Out[70]:

1-D arrays only allow concatenation on the same row, otherwise an error is
returned

In [75]: # concatenate 1-D arrays on the same columns when there is only 1 row returns an er

arr3=np.concatenate((arr1,arr2),axis=1)
arr3

#this is like forcefully creating a new row on arr1/ trying to stack 1-D arrays (py

---------------------------------------------------------------------------
AxisError Traceback (most recent call last)
Cell In[75], line 3
1 # concatenate 1-D arrays on the same columns when there is only 1 row retu
rns an error
----> 3 arr3=np.concatenate((arr1,arr2),axis=1)
4 arr3

File <__array_function__ internals>:200, in concatenate(*args, **kwargs)

AxisError: axis 1 is out of bounds for array of dimension 1

In [76]: # create 2-D arrays

arr1=np.eye(3)
arr2=np.ones((3,3))

print(arr1)
print()
print(arr2)

file:///C:/Users/USER/Documents/JOHN/Documents/EBE309/Numpy/11.1 NumPy.html 14/17


11/17/23, 12:04 PM 11.1 NumPy
[[1. 0. 0.]
[0. 1. 0.]
[0. 0. 1.]]

[[1. 1. 1.]
[1. 1. 1.]
[1. 1. 1.]]

In [77]: # concatenate 2-D arrays along the row axis

arr3=np.concatenate((arr1,arr2),axis=0)
arr3

# this is like stacking the arrays

array([[1., 0., 0.],


Out[77]:
[0., 1., 0.],
[0., 0., 1.],
[1., 1., 1.],
[1., 1., 1.],
[1., 1., 1.]])

In [ ]: arr3.shape

In [78]: # concatenate 2-D arrays along the column axis

arr3=np.concatenate((arr1,arr2),axis=1)
arr3

# this is link joining the arrays in series

array([[1., 0., 0., 1., 1., 1.],


Out[78]:
[0., 1., 0., 1., 1., 1.],
[0., 0., 1., 1., 1., 1.]])

In [ ]: arr3.shape

e). Reshaping arrays


We can modify the shape of an array using the reshape() function without
changing the total number of elements in the array.

You can reshape 1-D array to 2-D array and viceversa.

In [79]: # create array

arr=np.arange(1,11)
arr

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

In [80]: arr.shape

(10,)
Out[80]:

In [81]: # reshape (no.of rows,no. of columns)


# 1D to 2D

file:///C:/Users/USER/Documents/JOHN/Documents/EBE309/Numpy/11.1 NumPy.html 15/17


11/17/23, 12:04 PM 11.1 NumPy
arr1=arr.reshape(2,5)
arr1

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

In [82]: arr1.shape

(2, 5)
Out[82]:

In [83]: # 1D to 2D

arr1=arr.reshape(5,2)
arr1

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

In [84]: # 2D to 1D

arr3=arr1.reshape(10,)
arr3

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

In [ ]: arr3.shape

f). Statistical Operations on Arrays


In [85]: # create working array

arr=np.arange(1,11)
arr1=arr.reshape(5,2)
arr1

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

In [86]: # The max() function finds the maximum element from an array

arr1.max()

10
Out[86]:

In [87]: # The max() function finds the maximum element from an array by row

arr1.max(axis=0)

array([ 9, 10])
Out[87]:

In [88]: # The min() function finds the minimum element from an array

arr1.min()

file:///C:/Users/USER/Documents/JOHN/Documents/EBE309/Numpy/11.1 NumPy.html 16/17


11/17/23, 12:04 PM 11.1 NumPy
1
Out[88]:

In [89]: # The min() function finds the minimum element from an array by column

arr1.min(axis=1)

array([1, 3, 5, 7, 9])
Out[89]:

In [90]: # The sum() function finds the sum of all elements of an array

arr1.sum()

55
Out[90]:

In [91]: # The mean() function finds the average of elements of the array

arr1.mean()

5.5
Out[91]:

In [92]: # The std() function is used to find standard deviation of an array of elements

arr1.std()

2.8722813232690143
Out[92]:

ASSIGNMENT
1. Using create a 1-D array with 12 odd numbers between 1 and 24
2. Reshape the array to a 3 by 4 ndarray
3. Transpose the array
4. Create a new 3 by 4 identity ndarray
5. Join the first array to the second array along the columns
6. Calculate the mean and standard deviation of each column and store them in a
Python list

In [ ]:

file:///C:/Users/USER/Documents/JOHN/Documents/EBE309/Numpy/11.1 NumPy.html 17/17

You might also like