Numpy Practical Solution
Create a 5X2 integer array from a range between 100 to 200 such that the difference between each element is 10
import numpy
print("Creating 5X2 array using numpy.arange")
= numpy.arange(100, 200, 10)
sampleArray = sampleArray.reshape(5,2)
sampleArray print (sampleArray)
Creating 5X2 array using numpy.arange
[[100 110]
[120 130]
[140 150]
[160 170]
[180 190]]
Exercise 3: Following is the provided numPy array. Return array of items by taking the third column from all rows
import numpy
= numpy.array([[11 ,22, 33], [44, 55, 66], [77, 88, 99]])
sampleArray
print("Printing Input Array")
print(sampleArray)
print("\n Printing array of items in the third column from all rows")
= sampleArray[...,2]
newArray print(newArray)
Printing Input Array
[[11 22 33]
[44 55 66]
[77 88 99]]
Printing array of items in the third column from all rows
[33 66 99]
Exercise 4: Return array of odd rows and even columns from below numpy array
import numpy
= numpy.array([[3 ,6, 9, 12], [15 ,18, 21, 24],
sampleArray 27 ,30, 33, 36], [39 ,42, 45, 48], [51 ,54, 57, 60]])
[print("Printing Input Array")
print(sampleArray)
print("\n Printing array of odd rows and even columns")
= sampleArray[::2, 1::2]
newArray print(newArray)
Printing Input Array
[[ 3 6 9 12]
[15 18 21 24]
[27 30 33 36]
[39 42 45 48]
[51 54 57 60]]
Printing array of odd rows and even columns
[[ 6 12]
[30 36]
[54 60]]
Exercise 5: Create a result array by adding the following two NumPy arrays. Next, modify the result array by calculating the square of each element
import numpy
= numpy.array([[5, 6, 9], [21 ,18, 27]])
arrayOne = numpy.array([[15 ,33, 24], [4 ,7, 1]])
arrayTwo
= arrayOne + arrayTwo
resultArray print("addition of two arrays is \n")
print(resultArray)
for num in numpy.nditer(resultArray, op_flags = ['readwrite']):
= num*num
num[...] print("\nResult array after calculating the square root of all elements\n")
print(resultArray)
addition of two arrays is
[[20 39 33]
[25 25 28]]
Result array after calculating the square root of all elements
[[ 400 1521 1089]
[ 625 625 784]]
Exercise 7: Sort following NumPy array
Case 1: Sort array by the second row
Case 2: Sort the array by the second column
import numpy
print("\nPrinting Original array\n")
= numpy.array([[34,43,73],[82,22,12],[53,94,66]])
sampleArray print (sampleArray)
= sampleArray[:,sampleArray[1,:].argsort()]
sortArrayByRow print("\nSorting Original array by secoond row\n")
print(sortArrayByRow)
print("\nSorting Original array by secoond column\n")
= sampleArray[sampleArray[:,1].argsort()]
sortArrayByColumn print(sortArrayByColumn)
Printing Original array
[[34 43 73]
[82 22 12]
[53 94 66]]
Sorting Original array by secoond row
[[73 43 34]
[12 22 82]
[66 94 53]]
Sorting Original array by secoond column
[[82 22 12]
[34 43 73]
[53 94 66]]