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

Introduction to NumPy

Chapter 6 introduces NumPy, a Python library for numerical computing, including array manipulation and scientific functions. It covers installation via Pip, the differences between arrays and lists, and various array operations such as reshaping, slicing, and mathematical functions. The chapter also includes practical exercises for creating and manipulating NumPy arrays.

Uploaded by

cr7vk18shourya
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)
3 views

Introduction to NumPy

Chapter 6 introduces NumPy, a Python library for numerical computing, including array manipulation and scientific functions. It covers installation via Pip, the differences between arrays and lists, and various array operations such as reshaping, slicing, and mathematical functions. The chapter also includes practical exercises for creating and manipulating NumPy arrays.

Uploaded by

cr7vk18shourya
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/ 12

Chapter 6 – Introduction to NumPy

Exercise
Question 1:
What is NumPy ? How to install it?
Answer 1:

NumPy stands for Numerical Python and it is a python library used for working
with arrays. It also has various functions for scientific computing and working in
the domain of Fourier transform, linear algebra, and matrices. Travis Oliphant
created NumPy in 2005 and NumPy is an open-source project and we can use it
freely.

Installing NumPy:

We can install NumPy by using Pip. Pip is a package manager, which is used for
installing and managing Python software packages.

With Pip set up, we can use its command line for installing NumPy.

• pip install NumPy

Pip will download the NumPy package and notify when it has been successfully
installed.

Question 2:
What is an array and how is it different from a list? What is the name of the built-
in array class in NumPy?
Answer 2:

An array is a variable that can hold a fixed number of homogeneous items i.e. the
items of the array should be of the same type.

Difference between array and list:

The built-in array class in NumPy is called ndarray.

Question 3:
What do you understand by rank of an ndarray?
Answer 3:
Array in NumPy are of type ndarray and it is a table of elements (usually
numbers), all of the same data type, that are indexed by a tuple of positive
integers. The number of dimensions of the array in NumPy is called the rank of
the array. A tuple of integers that gives the size of the array along each
dimension of the array is called the shape of the array.
Question 4:
Create the following NumPy arrays:

Answer 4:
Question 5:
Using the arrays created in Question 4 above, write NumPy commands for the
following:

Answer 5:

(a) Lists of numerical data, vectors, and matrices are stored in NumPy arrays. For
creating, manipulating, and modifying NumPy arrays, the NumPy library includes
a wide number of built-in functions.

1.) ndarray.ndim :- returns the array's number of dimensions as an integer value.


Arrays can be one-dimensional, two-dimensional, or n-dimensional. The
dimensions are referred to as axes in NumPy. As a result, a two-dimensional
array has two axes. Axis-0 refers to the row axis, whereas axis-1 refers to the
column axis. The array's rank is also known as the number of axes.

2.) ndarray.shape :- returns a list of numbers representing the array's size for
each dimension.
3.) ndarray.size :- returns the array's total number of items. This is equal to the
sum of the shape elements.

4.) ndarray.dtype :- is the data type of the elements of the array. An array's
elements all have the same data type. Int32, int64, float32, float64, U32, and
other data types are common.

5.) ndarray.itemsize :- This property sets the size of each array element in bytes.
Each element of an array with the data types int32 and float32 takes up 32 bits of
memory. A byte is an 8-bit unit of measurement. As a result, an array of int32
entries has 32/8=4 bytes of itemsize. Int64/float64, on the other hand, denotes
that each item is 64/8=8 bytes in size.

(b) Reshape () :- Changing the form of an array is referred to as reshaping. The


number of items in each dimension determines the array's form. Example, We
can reshape an 4 elements 2D array into 2 elements in 2 rows 2D array, but not
into a 3 element 3 rows 2D array since 3x3 = 9 items would be required.

The numpy.reshape() function changes the shape of an array without changing


its data. Syntax :- numpy.reshape(array, shape, order = 'C')

where array is input array and shape is in which shape we want to change our
array. These two are required inputs. numpy array shapes must be in the from of
tuples. For example, a shape tuple for a 2 row and 3 column array will be (2,3).

NumPy commands to reshape the array "ones" to have all the 10 elements in a
single row : b=np.reshape(ones,(10,)) print(b)

(c) NumPy command to display the 2nd and 3rd element of the array vowels :-
print(vowels[1:3])

Code :- import numpy as np vowels = np.array(["a","e","i","o","u"]) print(" vowels


array elements ") print(vowels) print("2nd and 3rd element of the array vowels")
print(vowels[1:3]) // display the 2nd and 3rd element of array

(d) Command or Code to display all elements in the 2nd and 3rd row of the array
myarray1. :-

import numpy as np x= np.array([[2.7,-2,-19], [0,3.4,99.9],[10.6,0, 13]]) print("


myarray1 elements ") print(x) print("Display all elements in the 2nd and 3rd row
of the array myarray1") print(x[1]) // display all the element of second row
print(x[2]) // display all the element of third row
(e) Command or code to display elements in the 1st and 2nd column of the array
myarray1 :-

import numpy as np x= np.array([[2.7,-2,-19], [0,3.4,99.9],[10.6,0, 13]]) print("


myarray1 elements ") print(x) print("Display all elements in the 1st and 2nd
column of the array myarray1") print(x[:,0]) // display all the element of 1st
column print(x[:,1]) // display all the element of 2nd column

(f) NumPy command for given example :- print(x[-2:3,0])

Code to display the elements in the 1st column of the 2nd and 3rd row of the
array myarray1 :-

import numpy as np x= np.array([[2.7,-2,-19], [0,3.4,99.9],[10.6,0, 13]]) print("


myarray1 elements ") print(x) print("Display the elements in the 1st column of the
2nd and 3rd row of the array myarray1") print(x[-2:3,0]) //will return the 1st
column pf the 2nd and 3rd row

(g) NumPy command to reverse the array of vowels :- print(vowels[::-1]) Code :-


import numpy as np vowels = np.array(["a","e","i","o","u"]) print(" vowels array
elements ") print(vowels) print("Reversed array of vowels") print(vowels[::-1])
//reverse the elements present in array
Question 6:
Using the arrays created in Question 4 above, write NumPy commands for the
following:
Answer 6:

a) To divide each element of array by a scalar we can simply use the divide
operator as follows:

ones / 3

b) To add two arrays their shape must be same and we can use the following
method:

np.add( arr1, arr2)

But myarray1 has shape (3,3) whereas myarray2 has shape (3,5), so they cannot
be added.

c) To subtract two arrays their shape must be same and we can use the
following method:

np.subtract( arr1, arr2)

But myarray1 has shape (3,3) whereas myarray2 has shape (3,5), so they cannot
be subtracted.

d) To multiply two arrays element-wise their shape must be same and we can
use the following method:

np.multiply( arr1, arr2)

But myarray1 has shape (3,3) whereas myarray2 has shape (3,5), so they cannot
be multiplied.

e) To perform matrix multiply of two arrays, the column of first array should be
equal to the rows of second array and we can use the following method:

np.matmul( arr1, arr2)


So, here:

myarray3 = np.matmul(myarray1,myarray2)

f) To divide two arrays their shape must be same and we can use the following
method:

np.divide( arr1, arr2)

But myarray1 has shape (3,3) whereas myarray2 has shape (3,5), so they cannot
be divided.

g) To find the cube of elements of numpy array we can “np.power()” function, and
we need to provide the name of the array and the power in integer formate to be
calculated as follows:

np.power(myarray1,3)

To divide it by 2 we can simply use divide operator, as follows:

np.power(myarray1,3) / 2

h) To find the square root of a NumPy array we use the “np.sqrt()” function and
pass the array as an argument, as follows:

np.sqrt(myarray2)

To round of the elements to 2 decimal places we can use “np.round()” function


and pass the integer value of number of decimals up to which round off is to be
applied.

np.sqrt(myarray2).round(2)

Question 7:
Using the arrays created in Question 4 above, write NumPy commands for the
following:
Answer 7:

a) To find the transpose of an array we can use “np.T” function

So, the transpose of “ones” array can be found using:

• ones.T

And, transpose of “myarray2” array can be found using:

• myarray2.T

b) To sort an array we can use “np.sort” function and to sort in reverse we can
use negative indexing in the next step, as follows:

• vowels.sort()

• vowels[::-1]

c) To sort a 2-D array columnwise we can simply use “np.sort()” function and use
the default value of parameter “axis=-1”, as follows:

• myarray2.sort(axis=-1)

Question 8:
Using the arrays created in Question 4 above, write NumPy commands for the
following:
Answer 8:

a) The “numpy.spli()” function takes 3 arguments i.e., arr, indices_or_sections,


and axis, and their value is given according to the need. Here,

arr = myarray2 (array to be splited)

indices_or_sections = 5 ( number of sub-arrays)

axis = 1 (axis = 1 for columnwise)

So,

• myarray2A,myarray2B,myarray2C,myarray2D,myarray2E
=np.split(myarray2,indices_or_sections=5, axis=1)

To print the following sub arrays, we just pass them to print function.

print(myarray2A, myarray2B, myarray2C, myarray2D, myarray2E)

b) To split the array according to the index, we pass the value of indices as tuple,
as follows:

indices_or_sections = (2,5,7,8)

So,

• zerosA, zerosB, zerosC, zerosD, _ =


np.split(zeros,indices_or_sections=(2,5,7,8))

To print the following sub arrays, we just pass them to print function.

print(zerosA, zerosB, zerosC, zerosD)

c) To concatenate NumPy arrays we use the function “np.concatenate” and we


pass the arrays to be concatenated as a tuple and also assure the axis along
which concatenation is to be performed, as follows:

np.concatenate((myarray2A , myarray2B , myarray2C), axis = 1)

Question 9:
Create a 2-D array called myarray4 using arange() having 14 rows and 3 columns
with start value = -1, step size 0.25 having. Split this array row wise into 3 equal
parts and print the result.
Answer 9:

Here we have to create a 2-D array of shape (14,3), that means there should be
42 elements in the array, based on this we will define the values to be passed to
the function “np.arange()”, that are as follows:

Start = -1 (Given)

Stop = 9.5 (Calculated to fit exactly 42 elements in array)

Step = 0.25 (Given)

So, now we can create a new array using “np.arange()”, as follows:

myarray4 = np.arange(start=-1, stop=9.5, step=0.25)

To define the columns as 14 and rows as 3, we can use “np.reshape()” function,


as follows:

myarray4 = myarray4.reshape((14,3))

Question 10:
Using the myarray4 created in the above questions, write commands for the
following:
a) Find the sum of all elements.
b) Find the sum of all elements row wise.
c) Find the sum of all elements column wise.
d) Find the max of all elements.
e) Find the min of all elements in each row.
f) Find the mean of all elements in each row.
g) Find the standard deviation column wise.
Answer 10:

a) To find the sum of all the elements of an array we can use the function
“np.sum()”, as follows:

myarray4.sum()
b) To find the sum of the elements row-wise, we can use the axis argument of
the function “np.sum()”, and for row-wise calculation axis = 1.

So,

myarray4.sum(axis = 1)

will give the sum of the elements row-wise.

c) To find the sum of the elements column-wise, we can use the axis argument of
the function “np.sum()”, and for column-wise calculation axis = 0.

So,

myarray4.sum(axis =0)

will give the sum of the elements column-wise.

d) To find the max among all the elements row-wise, we can use the function
“np.max()”, as follows:

myarray4.max()

will give the maximum element in that array.

e) To find the min among all the elements row-wise, we can use the axis
argument of the function “np.min()”, and for row-wise calculation, axis = 1.

So,

myarray4.min(axis = 1)

will give the min among the elements row-wise.

f) To find the mean of the elements row-wise, we can use the axis argument of
the function “np.mean()”, and for row-wise calculation, axis = 1.

So,

myarray4.mean(axis = 1)

will give the mean of the elements row-wise.


g) To find the standard deviation of the elements column-wise, we can use the
axis argument of the function “np.std()”, and for column-wise calculation axis =
0.

So,

myarray4.std(axis = 0)

will give the standard deviation of the elements column-wise.

You might also like