Lets Begin With Numpy
Lets Begin With Numpy
1
7. np.identity() or np.eye()
0.3.1 1. np.array()
# We can pass a list and specify a datatype (optional) in which we want to␣
↪store the value in array
arr_1d
[3]: dtype('int32')
[4]: (5,)
[6]: (2, 3)
2
[8]: array([[1, 2, 3, 4, 5, 6]])
[10]: (4,)
[11]: dtype('float64')
0.3.2 2. np.arange()
We can create an array with a range of elements
[12]: # Create an array from 1 to 10
np.arange(start=1, stop=10)
[14]: (5,)
[15]: # Convert to 2D
np.arange(1,10,2).reshape(5,1).shape
[15]: (5, 1)
[16]: np.arange(50,1,-1)
[16]: array([50, 49, 48, 47, 46, 45, 44, 43, 42, 41, 40, 39, 38, 37, 36, 35, 34,
33, 32, 31, 30, 29, 28, 27, 26, 25, 24, 23, 22, 21, 20, 19, 18, 17,
3
16, 15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2])
[17]: np.arange(1,18,3)
np.arange(1,18,3).shape
np.arange(1,18,3).reshape(2,3)
0.3.3 3. np.linspace()
We can create an array with values that are spaced linearly in a specified interval
[18]: # linspace -- equally spaced elements
[19]: # reshaping
np.linspace(1,20,30).reshape(3,10)
0.3.4 4. np.zeros()
We can create an array filled with 0’s
[20]: # zeros
np.zeros(3)
[21]: # zeros
np.zeros((3,4))
4
[21]: array([[0., 0., 0., 0.],
[0., 0., 0., 0.],
[0., 0., 0., 0.]])
0.3.5 5. np.ones()
We can create an array filled with 1’s
[22]: # ones
np.ones(3)
[23]: # ones
np.ones((3,4))
[24]: # ones
np.ones((5,2,8))
# 2,8 denotes the inner most array of 2 rows and 8 columns
# and there are 5 sets of 2,8 arrays making it 3D array
0.3.6 6. np.empty()
We can create an array whose initial content is random and depends on the state of the memory.
The reason to use empty over zeros is speed - just make sure to fill every element afterwards!
[25]: # empty
np.empty((3,7))
5
[25]: array([[0., 0., 0., 0., 0., 0., 0.],
[0., 0., 0., 0., 0., 0., 0.],
[0., 0., 0., 0., 0., 0., 0.]])
0.3.7 7. np.identity()
Return the identity array.
The identity array is a square array with ones on the main diagonal and others are zeros
[26]: # identity matrix of 4x4 shape
np.identity(4)
np.sort(arr)
[4 3 6 7 1 9]
6
[30]: # Concatenating different sizes of array by axis=1
a = np.array([[1,2], [3,4]])
b = np.array([[5,6]])
np.concatenate((a,b.T), axis=1)
0.5.1 ndarray.ndim
tells us the number of axes, or dimensions, of the array.
[31]: arr = np.array([[[0, 1, 2, 3], [4, 5, 6, 7]],
[[0, 1, 2, 3], [4, 5, 6, 7]],
[[0 ,1 ,2, 3], [4, 5, 6, 7]]])
arr.ndim # gives the dimension of the array
[31]: 3
0.5.2 ndarray.size
finds total number of elements in the array
[32]: arr.size
[32]: 24
0.5.3 ndarray.shape
finds the shape of the array
[33]: arr.shape
[33]: (3, 2, 4)
7
print(arr)
print()
[ 0 1 2 3 4 5 6 7 8 9 10 11]
[[ 0 1 2 3 4 5]
[ 6 7 8 9 10 11]]
[[ 0 1 2]
[ 3 4 5]
[ 6 7 8]
[ 9 10 11]]
[[[ 0 1]
[ 2 3]]
[[ 4 5]
[ 6 7]]
[[ 8 9]
[10 11]]]
0.7.1 np.random.rand()
Random number generation (Uniform distribution)
[35]: np.random.rand(2,3)
8
0.7.2 np.random.randn()
Random number generation (Normal distribution with Mean=0 & Standard Deviation=1)
[36]: np.random.randn(2,3)
0.7.3 np.random.randint()
Return random integers from the “discrete uniform” distribution of the given size from low (inclu-
sive) to high (exclusive)
[37]: array([12, 45, 68, 54, 65, 43, 79, 94, 96, 28])
0.7.4 np.random.random_sample()
Return random floats in the half-open interval [0.0, 1.0).
[72]: np.random.random_sample(size=(2,6))
0.7.5 np.random.normal()
Draw random samples from a normal (Gaussian) distribution
9
0.8 Indexing and slicing of Arrays
We can index and slice NumPy arrays in the same way we slice Python lists.
[39]: arr = np.arange(0,11)
arr
[40]: 1
[45]: # print all of the values in the array that are less than equal to 5
arr[arr<=5]
[46]: # select elements that satisfy two conditions using the & and | operators
arr[(arr<=8) & (arr>2)]
10
0.8.1 Problem statement
[47]: arr1 = np.random.randint(2,100,20).reshape(5,4)
arr1
[48]: # all data till 3rd row and all data till 3rd column
arr1[:3,:3]
[49]: # all data starting from 3rd row and all data starting from 1st column
arr1[3:,1:]
[50]: # all data starting from 2nd row till 3rd row and all data of 1st and last␣
↪column
arr1[2:4,[0,-1]]
print(f"\nArray2: \n{arr2}")
Array1:
[[18 14]
11
[ 7 4]]
Array2:
[[15 10]
[10 16]]
Addition:
[[33 24]
[17 20]]
Subtraction:
[[ 3 4]
[ -3 -12]]
Multiplication:
[[270 140]
[ 70 64]]
Division:
[[1.2 1.4 ]
[0.7 0.25]]
[55]: # sum
print(arr1)
print("Sum without axis", arr1.sum())
print("Sum axis=0", arr1.sum(axis=0))
print("Sum axis=1", arr1.sum(axis=1))
[[18 14]
[ 7 4]]
Sum without axis 43
Sum axis=0 [25 18]
Sum axis=1 [32 11]
[56]: # Addition
arr1 + arr2
[57]: np.sqrt(arr1)
12
[57]: array([[4.24264069, 3.74165739],
[2.64575131, 2. ]])
[58]: np.exp(arr2)
[59]: np.log10(arr1)
[61]: # Broadcasting | NumPy understands that the multiplication should happen with␣
↪each cell. That concept is called broadcasting.
arr1 = arr.copy()
print(arr)
13
arr1[3:] = 500
print(arr1)
Vertical Stack:
[[1 1]
[2 2]
[3 3]
[4 4]]
Horizontal Stack:
[[1 1 3 3]
[2 2 4 4]]
[64]: array([11, 11, 12, 13, 14, 15, 16, 17, 12, 13, 11, 14, 18, 19, 20])
unique_values
[73]: array([11, 12, 13, 14, 15, 16, 17, 18, 19, 20])
[11 12 13 14 15 16 17 18 19 20]
[ 0 2 3 4 5 6 7 12 13 14]
14
print(counts)
[11 12 13 14 15 16 17 18 19 20]
[3 2 2 2 1 1 1 1 1 1]
1 NumPy: Exercises
[79]: # Write a NumPy program to create an array of all even integers from 30 to 70.
[79]: array([30, 32, 34, 36, 38, 40, 42, 44, 46, 48, 50, 52, 54, 56, 58, 60, 62,
64, 66, 68])
[98]: # Write a NumPy program to create a 2D array with 1 on the border and 0 inside.
arr = np.ones((5,5))
arr[1:-1, 1:-1] = 0
arr
[106]: # Write a NumPy program to test whether each element of a 1-D array is also␣
↪present in a second array.
15
# if arr1[i] in arr2:
# arr1[i] = True
# else:
# arr1[i] = False
print("Compare each element of array1 and array2")
np.in1d(arr1, arr2)
[118]: # Write a Python program to find the maximum and minimum value of a given␣
↪flattened array.
Max: 3
Min: 0
16