Programming Examples
Create a numpy array having two dimensions and shape(3,3) and perform the following operations on array elements:
Create a numpy array having two dimensions and shape(3,3) and perform the following operations on array elements:
a) Calculate sum of all the columns of the array
b) Calculate product of all the rows of the array.
c) Retrieve only the last two columns and last two rows form the array.
d) Create another two dimensional array having same shape and carry out element wise addition of two arrays and display the result.
Create a new array by multiplying every element of original array with value 2 and display the new array.
Solution
import numpy as np
arr=np.array([[3,4,9],[3,4,2],[1,2,3]])
print("Array is : \n",arr)
print("Sum of All Column ",np.sum(arr, axis=0))
print("Product of All Column ",np.prod(arr, axis=0))
print("Last Two Column \n",arr[:, -2:])
print("Last Two Rows \n",arr[-2:, :])
arr1=np.array([[4,5,6],[7,8,3],[2,2,1]])
print("Second Array is : \n",arr1)
print("Addition of 2 Array is : \n",(arr+arr1))
arr3=arr * 2
print("Third Array (Muliply by 2) : \n",arr3)
Output
Array is :
[[3 4 9]
[3 4 2]
[1 2 3]]
Sum of All Column [ 7 10 14]
Product of All Column [ 9 32 54]
Last Two Column
[[4 9]
[4 2]
[2 3]]
Last Two Rows
[[3 4 2]
[1 2 3]]
Second Array is :
[[4 5 6]
[7 8 3]
[2 2 1]]
Addition of 2 Array is :
[[ 7 9 15]
[10 12 5]
[ 3 4 4]]
Third Array (Muliply by 2) :
[[ 6 8 18]
[ 6 8 4]
[ 2 4 6]]