10.1 Numpy Basics
10.1 Numpy Basics
Lecture-20
Array Indexing
Slicing Arrays
Using Python, it is possible to
select a range of elements from
an array by using the slice
operator (:)
[START POSITION]:[END
POSITION]
One thing to note is that the end
index position is never included
as part of the result of a slice.
For example, if you use [1:5],
you are effectively saying 1 to 5,
where the data in index position
5 is not included in the result
Array Slicing Example
import numpy as np
a = np.array([1,2,3,4,5,6,7,8])
print(a[:]) #Beginning to end
print(a[:3])#Beginning to
index position 3
print(a[3:])#Position 3 to endOutput
print(a[2:4])#Position 2 to 4 [1 2 3 4 5 6 7 8]
a[2]=777 [1 2 3]
print(a) [4 5 6 7 8]
[3 4]
[ 1 2 777 4 5 6
7 8]
Example 5
Output
1
3
11
14
Example 6
Example 7
Example 5
import numpy as np Output
[ 0 1 2 3 4 5 6 7 8 9 10
a = np.arange(12) 11]
print(a) [[[ 0 1 2 3]
# now reshape it [ 4 5 6 7]
[ 8 9 10 11]]]
# b is having three
[[[ 0 1]
dimensions
[ 2 3]]
b = a.reshape(1,3,4)
# 3row,4col,1array [[ 4 5]
print (b) [ 6 7]]
b = a.reshape(3,2,2)
[[ 8 9]
# 2row,2col,3array
[10 11]]]
print (b)
75. Add two Matrices
Output
[17, 15, 4]
[10, 12, 9]
[11, 13, 18]
76. Multiply two Matrices
76. Output
[114, 160, 60, 27]
[74, 97, 73, 14]
[119, 157, 112, 23]
76.Explanation
In Python, we can implement a matrix as nested list
(list inside a list).We can treat each element as a
row of the matrix. For example X = [[1, 2], [4, 5], [3,
6]] would represent a 3x2 matrix.
The first row can be selected as X[0]. And, the
element in first row, first column can be selected
as X[0][0]. Multiplication of two matrices X and Y is
defined only if the number of columns in X is equal
to the number of rows Y.
If X is a n x m matrix and Y is a m x l matrix
then, XY is defined and has the dimension n x
l (but YX is not defined). Here are a couple of ways
to implement matrix multiplication in Python.
77. Transpose of Matrix
Output
[12, 4, 3]
[7, 5, 8]
Armstrong number is a number that is equal
to the sum of cubes of its digits. For example
0, 1, 153, 370, 371 and 407 are the Armstrong
numbers.
78.Check number is
Armstrong?
78. Output
Enter a number: 56
56 is not an Armstrong number
Explanation
Here, we ask the user for a number and
check if it is an Armstrong number. We
need to calculate the sum of the cube of
each digit. So, we initialize the sum to 0
and obtain each digit number by using
the modulus operator %. The remainder of
a number when it is divided by 10 is the
last digit of that number. We take the cubes
using exponent operator.
Finally, we compare the sum with the
original number and conclude that it is
Armstrong number if they are equal.