Numpy
Numpy
shape
NumPy - Numerical Python
(2, 4)
import numpy as np
Initial Placeholders in numpy arrays
List vs Numpy - Time Taken
# create a numpy array of Zeros
x = np.zeros((4,5))
from time import process_time print(x)
[[0. 0. 0. 0. 0.]
Time taken by a list [0. 0. 0. 0. 0.]
[0. 0. 0. 0. 0.]
[0. 0. 0. 0. 0.]]
python_list = [i for i in range(10000)]
0.0017722080000002194
# array of a particular value
z = np.full((5,4),5)
np_array = np.array([i for i in range(10000)]) print(z)
[[1. 0. 0. 0. 0.]
Numpy Arrays [0. 1. 0. 0. 0.]
[0. 0. 1. 0. 0.]
[0. 0. 0. 1. 0.]
# list [0. 0. 0. 0. 1.]]
list1 = [1,2,3,4,5]
print(list1)
type(list1) # create a numpy array with random values
b = np.random.random((3,4))
[1, 2, 3, 4, 5] print(b)
list
[[0.06180442 0.35700298 0.90695408 0.03091635]
[0.58655837 0.66048197 0.29741526 0.89522409]
np_array = np.array([1,2,3,4,5]) [0.75529751 0.8197227 0.89382064 0.85936446]]
print(np_array)
type(np_array)
# random integer values array within a specific range
[1 2 3 4 5] c = np.random.randint(10,100,(3,5))
numpy.ndarray print(c)
[[24 82 43 91 73]
# creating a 1 dim array [98 11 52 38 38]
a = np.array([1,2,3,4]) [13 68 44 21 11]]
print(a)
[1 2 3 4] # array of evenly spaced values --> specifying the number of values required
d = np.linspace(10,30,5)
print(d)
a.shape
[10. 15. 20. 25. 30.]
(4,)
array = np.random.randint(0,10,(2,3))
# checking the data type of the values in the array
print(array)
print(c.dtype)
print(array.shape)
int64
[[1 2 2]
[8 0 7]]
(2, 3)
Mathematical operations on a np array
# transpose
list1 = [1,2,3,4,5] trans = np.transpose(array)
list2 = [6,7,8,9,10] print(trans)
print(trans.shape)
print(list1 + list2) # concatenate or joins two list
[[1 8]
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10] [2 0]
[2 7]]
(3, 2)
a = np.random.randint(0,10,(3,3))
b = np.random.randint(10,20,(3,3))
array = np.random.randint(0,10,(2,3))
print(array)
print(a)
print(array.shape)
print(b)
[[8 1 0]
[[7 2 0] [2 5 9]]
[8 8 6] (2, 3)
[5 7 0]]
[[15 10 13]
[18 14 14] trans2 = array.T
[12 13 10]] print(trans2)
print(trans2.shape)
print(a+b)
[[8 2]
print(a-b)
[1 5]
print(a*b)
[0 9]]
print(a/b) (3, 2)
[[22 12 13]
[26 22 20] # reshaping a array
[17 20 10]] a = np.random.randint(0,10,(2,3))
[[ -8 -8 -13] print(a)
[-10 -6 -8]
print(a.shape)
[ -7 -6 -10]]
[[105 20 0]
[[4 3 7]
[144 112 84]
[4 6 6]]
[ 60 91 0]]
(2, 3)
b = a.reshape(3,2)
print(b)
print(b.shape)
[[4 3]
[7 4]
[6 6]]
(3, 2)