Numpy - array manipulation
# numpy
import numpy as np
import random
# Creating a random 2d array object
M1 = np.random.randint(10, size=(2,2))
M2= np.random.randint(10, size=(2,2))
print("Generated array object")
print(M1)
print(M2)
# Array operations
print("Array operations")
print("Sum")
print(np.add(M1,M2))
print("Difference")
print(np.subtract(M1,M2))
print("Product")
print(np.dot(M1,M2))
print("Division")
np.set_printoptions(precision=2)
print(np.divide(M1,M2))
"""
Sample output
>python 8_5_numpy2.py
Generated array object
[[8 3]
[0 7]]
[[8 5]
[5 6]]
Array operations
Sum
[[16 8]
[ 5 13]]
Difference
[[ 0 -2]
[-5 1]]
Product
[[79 58]
[35 42]]
Division
[[1. 0.6 ]
[0. 1.17]]
"""
Numpy - Creating arrays
# numpy
import numpy as np
import random
# Creating a random 2d array object of size 2 x 3
M1 = np.random.randint(10, size=(2,3))
print("Generated array object")
print(M1)
# About array object
print("About array object")
print("Type : ", type(M1))
# Array dimensions (axes)
print("Number of dimensions : ", M1.ndim)
# Shape shape of array
print("Shape of array: ", M1.shape)
# Size (total number of elements)
print("Size of array (total number of elements) : ", M1.size)
# Data type of elements in array
print("Data type : ", M1.dtype)
# Manipulation of array data
print("Data manipulation")
print("Sum of all elements : ",np.sum(M1))
print("Sum of column elements")
print(np.sum(M1,axis=0))
print("Sum of row elements")
print(np.sum(M1,axis=1))
# Transpose of the 2d array
print("Transpose")
print(M1.T)
"""
Sample output
>python 8_5_numpy1.py
Generated array object
[[1 6 9]
[0 6 3]]
About array object
Type : <class 'numpy.ndarray'>
Number of dimensions : 2
Shape of array: (2, 3)
Size of array (total number of elements) : 6
Data type : int32
Data manipulation
Sum of all elements : 25
Sum of column elements
[ 1 12 12]
Sum of row elements
[16 9]
Transpose
[[1 0]
[6 6]
[9 3]]
"""