Ex 2
Ex 2
OBJECTIVE: To print the dimension, shape and the number of bytes of an array.
1 IMPORT
[27]: import numpy as np
np.random.seed(0)
x1 = np.random.randint(10, size=6)
x2 = np.random.randint(10, size=(3, 4))
x3 = np.random.randint(10, size=(3, 4, 5))
3
dtype: int32
[55]: x1
2 POSITIVE INDEXING
[57]: x1
[60]: x1[5]
[60]: 9
3 NEGATIVE INDEXING
[64]: x1[-2]
[64]: 7
1
[66]: x1[-4]
[66]: 3
[68]: 8
[70]: x2[0,0]
[70]: 3
5 MODIFYING IN ARRAY
[83]: x2[1, 2] = 11
x2
6 SUB ARRAY
[98]: x= np.arange(15)
x
7 SLICING
[102]: x[:4]
[123]: x[8:16]
2
8 MULTI DIM ARRAY
[125]: x2
[127]: x2
[[3 5]
[134]: [7 6]
[1 6]]
print(x2[:, 0])
[3 7 1]
[156]: array([[1],
[2],
[3]])
3
11 Array Concatenation and Splitting
[162]: x=np.array([1])
y=np.array([4,3])
np.concatenate([x,y])
[168]: m=np.array([3])
np.concatenate([x,y,])
[169]: np.concatenate([x,y,m])
12 Splitting of arrays
[176]: x = [1, 2, 3, 99, 99, 3, 2, 1]
x1, x2, x3 = np.split(x, [3, 5])
print(x1, x2, x3)
[1 2 3] [99 99] [3 2 1]
[[ 0 1 2 3 4 5 6 7 8]
[ 9 10 11 12 13 14 15 16 17]]
[[18 19 20 21 22 23 24 25 26]
[27 28 29 30 31 32 33 34 35]
[36 37 38 39 40 41 42 43 44]]
4
print(right)
[[ 0]
[ 9]
[18]
[27]
[36]]
[[ 1 2 3 4 5 6 7 8]
[10 11 12 13 14 15 16 17]
[19 20 21 22 23 24 25 26]
[28 29 30 31 32 33 34 35]
[37 38 39 40 41 42 43 44]]
for i in range(len(values)):
output[i] = 1.0 / values[i]
return output
values = np.random.randint(1, 10, size=5)
compute_reciprocals(values)
14 UFuncs
[30]: import numpy as np
np.random.seed(0)
def compute_reciprocals(values):
output = np.empty(len(values))
for i in range(len(values)):
output[i] = 1.0 / values[i]
return output
5
[253]: print(compute_reciprocals(values))
print(3.1 / values)
15 Array arithmetic
[8]: import numpy as np
x = np.arange(4)
print("x =", x)
print("x + 5 =", x + 5)
print("x - 5 =", x - 5)
print("x * 2 =", x * 2)
x = [0 1 2 3]
x + 5 = [5 6 7 8]
x - 5 = [-5 -4 -3 -2]
x * 2 = [0 2 4 6]
[9]: -(0.5*x + 1) ** 2
16 Absolute value
[13]: X = np.array([-2, -1, 0, 1, 2])
abs(x)
# Trignometric functions
[16]: theta = np.linspace(0, np.pi, 3)
6
[22]: x = [-1, 0, 1]
print("x = ", x)
print("arcsin(x) = ", np.arcsin(x))
print("arccos(x) = ", np.arccos(x))
print("arctan(x) = ", np.arctan(x))
x = [-1, 0, 1]
arcsin(x) = [-1.57079633 0. 1.57079633]
arccos(x) = [3.14159265 1.57079633 0. ]
arctan(x) = [-0.78539816 0. 0.78539816]
[ ]:
INFERENCE: Numpy, pandas, scipy, seaborn and statsmodels packages
were installed