Numpy - Arrays
Numpy arrays are similar to lists, the only difference is that, we can only store the same type of variables, unlike lists where we can save different types of variables.
Thus, making it very compact and faster compared to lists.
Eg:- Lists, li = [1, 2, 3.4, "Hello"] this is possible in the case of lists, while in the case of NumPy arrays npArr = [1, 2, 3.4, "Hello"] will throw an error.
Instead, we can use it like npArr = [1, 2, 3, 4] or npArr = ["Hello", "World"] etc.
1) Import the library
import numpy as np // Method 1
import numpy // Method 2
// Method 1 is used when you have multiple occasions where you have to write numpy, again and again, to call the functions in it. Hence, making it simpler by just using the shorthand np.
2) creating a numpy array
/ Method 1 - converting the existing list into numpy array
li = [1, 2, 3]
np.array(li)
/ Method 2 - Array full of zeros of size 10
a0 = np.zeros(10)
print(a.dtype) # returns the type of the data by default it is a float
/ Method 3 - Array full of ones of size 10
a1 = np.ones(10)
a1_int = np.ones(10, int) # changing default data type is also possible
/ Note: other size options are also possible like 100, 5, 20 etc.
2.1) creating 2d arrays
a_2d = np.zeros((2, 3)) # pass a tuple instead of just a number
li_2d = [[1, 2, 3], [4, 5, 6]]
np.array(li_2d)
Note: For n-dimensional, give the n's as tuple eg:- (2, 2, 2), (2, 3, 4, 5) etc
3) changing particular index value
a0[0] = 1 # similar to how list works
Note: if we give another data type other than the already applied one, it gets converted into the existing type automatically
a0[0] = "1" # "1" will get converted float
Note: However, if we give a actual string like "Hello", "hi" etc, it will throw an error.
4) Accessing elements -> exactly same as how list works
print(li[0])
/ for 2d arrays
li1_2d = np.array([[11, 12, 13], [14, 15, 16]])
print(li1_2d[0]) # accessing 0th row
print(li1_2d[:, 0]) # accessing 0th column
/ little more interesting
li2_2d = np.array([[11, 12, 13], [14, 15, 16], [11, 12, 13], [14, 15, 16]])
print(li2_2d[:, 0])
print(li2_2d[0:2, 0])
print(li2_2d[:, 1:3])
5) Slicing -> -> exactly same as how list works
print(li[1:2])
print(li_2d[1:2])
6) Size of the array
print(a0.shape)