Good day everybody! At present we kick off our deep dive into important Python libraries — beginning with NumPy. Watching this NUMPY TUTORIAL.
NumPy is an open‑supply library for quick, reminiscence‑environment friendly n‑dimensional arrays and vectorized math operations, all powered by optimized C code. It additionally gives constructed‑in statistical and linear algebra features.
💡 For blended‑kind information (strings, dates), use Pandas as a substitute.
- Pace & Effectivity: C‑backed arrays run math on massive datasets a lot quicker than lists.
- Vectorization: Apply operations to complete arrays with out specific loops.
- Broadcasting: Carry out factor‑clever math on arrays of various shapes robotically.
Creating Arrays: You may create arrays with np. array() and entry parts utilizing indexing
import numpy as np
a = np.array([1, 2, 3, 4, 5, 6])
print(a)
# => [1 2 3 4 5 6]
Indexing and Modification
print(a[2]) # => 3
a[3] = 13
print(a) # => [ 1 2 3 13 5 6]
Slicing: Slicing works equally to Python lists
1. a[3:]
OP => array([13, 5, 6])
a[:2]
OP => arr([1,2])2. b = a[4:]
OP => arr([5,6]) # you may as well assign to different variable & print
Array Attributes: NumPy arrays include constructed‑in attributes to examine their construction:
1. # 0-D array(scalar)
a= np.array(23)
print(a.ndim,a.form,a.measurement,len(a.form))
#=> No of Dimensions: 0 #=> Form:() #=> Len of Form: 0 #=> Measurement: 1 - Form is empty becuase it's non destructive quantity that specify the variety of elemnts
alongside every dimension however on this case we have now dimension as 0.
- Len of Form is at all times equal to no. of dimensions.
- Measurement is not any of parts.(or product of all parts in form)
2. # 1-D array
a= np.array([1.2])
print(a.ndim,a.form,a.measurement,len(a.form))
#=> No of Dimensions: 1 #=> Form- (2,) #=> Len of Form: 1 #=> Measurement: 2
3.# 2-D array
a= np.array([[1,2],
[1,2]])
print(a.ndim,a.form,a.measurement,len(a.form))
#=> No of Dimensions: 2 #=> Form- (2,2) #=> Len of Form: 2 #=> Measurement: 4
a= np.array([[1, 2, 3],
[4, 5, 6],
[7, 8, 9]])
print(a.ndim,a.form,a.measurement,len(a.form))
#=> No of Dimensions: 2 #=> Form- (3,3) #=> Len of Form: 2 #=> Measurement: 12
5. # 3-D array
a= np.array([[[1,2,6,7],
[1,2,6,7]],
[[1,2,6,7],
[1,2,6,7]]])
print(a.ndim,a.form,a.measurement,len(a.form))
#=> No of Dimensions: 3 #=> Form- (2,2,4) #=> Len of Form: 2 #=> Measurement: 12
6. # 4-D array
a= np.array([[[[1,2,6,7],
[1,2,6,7]],
[[1,2,6,7],
[1,2,6,7]]],
[[[1,2,6,7],
[1,2,6,7]],
[[1,2,6,7],
[1,2,6,7]]]])
print(a.ndim,a.form,a.measurement,len(a.form))
#=> No of Dimensions: 4 #=> Form- (2,2,2,4) #=> Len of Form: 2 #=> Measurement: 12
Knowledge Sort: dtype()
Knowledge Sort (dtype): You may test the info kind of array parts
a = np.array([1, 2, 3], dtype=np.int32)
a.d(kind) #=> 'int32'
np.zeros() and np.ones(): Creating arrays full of all zeros or ones.
1. a = np.zeros(2)
array([0., 0.]) 2. However you may as well give form and outline each single factor in it
a = np.zeros((2,3,7,4))
# Right here we have now 2 dimensions with 3 parts every having 7 columns and 4 rows
3. Equally for ones as a substitute of 0 it should fill the array with ones
np.ones((2,3,6)) #=> 2×3×4 array of 1.0
# Right here we have now 2 dimensions every having 6 columns and three rows.
np.empty(): Ceates an array with random preliminary content material, which is quicker.
1. np.empty(2) #=> array([1.05463191e-311, 1.05658269e-311]) rubbish worth2. To print sure form of rubbish values (uninitialized)
np.empty((3,8))
Why use empty? It’s quicker than zeros/ones while you plan to overwrite each factor.
np.arange(): Creates arrays with a variety of values. Like Python’s
vary
, however returns an array:
Format:(first quantity, final quantity, step measurement)
1. np.arange(2,9,2) #=> array([2, 4, 6, 8]) cease is unique
2. np.arange(6) #=> array([0, 1, 2, 3, 4, 5]) takes default begin 0 and 1 step
np.linspace(): Generates N evenly spaced factors together with endpoints:
Format(first quantity, final quantity , no of parts you need)
np.linspace(0, 10, num=5) #=> array([ 0. , 2.5, 5. , 7.5, 10. ]) cease is unique
'''Step measurement = (finish – begin) / (num – 1)
Right here: (10 – 0) / 4 = 2.5'''
📌 Tip: To transform it into integer we will do:-
x = np.ones(2, dtype = np.int64)
Output:- array([1, 1]) Do the identical factor in every single place!
np.type(): Kinds array parts & np.concatenate() : Joins arrays alongside a specified axis
arr = np.array([2,1,5,3,7,4,6,8])
arr2 = np.array([24,52,43,14,25,56])
1. # Type
np.type(arr) # ⇒ [1 2 3 4 5 6 7 8]
np.argsort(arr) # ⇒ [1 0 3 5 2 6 4 7] # Type and return indices2. # Partition all parts < kth place come first (unordered)
np.partition(arr, 3) # ⇒ [1 2 3 4 5 7 6 8]
3. # Concatenate
np.concatenate((arr, arr2)) # ⇒ [ 2 1 5 3 7 4 6 8 24 52 43 14 25 56]4.
# 2-D concatenation
axis=0 provides rows; axis=1 provides columns
a = np.array([[1,2],[3,4]])
b = np.array([[5,6]])
np.concatenate((a, b), axis=0) # Shapes should match, besides the axis you’re stacking alongside
=>[[1 2]
[3 4]
[5 6]]
np.reshape(): Modifications the form of an array
1. a= np.arange(1,7) #=> array([1, 2, 3, 4, 5, 6])
a.reshape(2,3) #=> array([[1, 2, 3], [4, 5, 6]]) Reshapes the array2. a= np.arange(6)
np.reshpae(a, (2,3), order='F') #=> array([[0, 2, 4], [1, 3, 5]]) Reshapes column clever
np.reshape(a, (2,3), order='C') #=> array([[0, 1, 2], [3, 4, 5]]) Reshapes row clever
np.newaxis() or np.expand_dims(): Provides a brand new dimension to an array
a = np.array([1,2,3,4,5,6])
a.form Form is #=> (6,)If we add new axis
1. a2 = a[np.newaxis, :]
a2.form #=> A brand new row vector will get added and Form turns into (1,6)
2. a2 = a[:, np.newaxis,]
a2.form #=> A brand new column vector will get added and Form turns into (6,1)
Equal utilizing expand_dims
1. b = np.expand_dims(a, axis =0)
b.form #=> A brand new column vector will get added #=>(1,6)
2. c = np.expand_dims(a, axis =1)
c.form #=> A brand new row vector will get added #=>(6,1)
Situation primarily based Slicing
arr = np.array([12, 89, 45, 31, 789, 200])
masks = arr < 50 # ⇒ [True False True True False False]
arr[mask] # ⇒ [12 45 31]# 2D masks & nonzero
mat = np.array([[13,62,3,42],
[75,6,7,84],
[93,10,2,21]])
mat < 50 # ⇒ array of True/False
np.nonzero(mat < 50) # ⇒ (row_indices, col_indices) Will get you indices
Stacking: np.vstack() (vertical) and np.hstack() (horizontal) & Splitting: np.hsplit()
a = np.array([1,2,3])
b = np.array([4,5,6])
#Stacking
1. Vertical stack (np.vstack)
np.vstack((a, b)) # => [[1,2,3],
# [4,5,6]]
2. Horizontal stack (np.hstack)
np.hstack((a, b)) #=> [1,2,3,4,5,6]# Splitting
1. x = np.arange(8)
np.hsplit(x, 4) #=> [array([0,1]), array([2,3]), array([4,5]), array([6,7])]
2. np.hsplit(x, (3,4,7)) #=> [array([0,1,2]), array([3]), array([4,5,6]), array([7])]
Views vs Copies
arr= np.arange(6)
1. View: Shares reminiscence with the unique array
arr = np.arange(6)
v = arr[1:4]
v[0] = 99 # additionally modifications arr[1] => array([0,99,2,3,4,5])2. Copy: An impartial array
c = arr.copy()
c[0] = –1 # arr unchanged array([0,1,2,3,4,5])
Aspect‑clever math & Aggregations
1. a + b, a-b, a * b, a / b #each of them ought to have similar form although! 2. arr= np.arange(1,10).reshape(3,3)
arr.sum() #return sum of all parts
# Axis-specific sums
a.sum(axis=0) # column sums
a.sum(axis=1) # row sums
3. arr.min(), arr.max() # Returns Max and Min Aspect from array
Return column clever or do the identical row clever with:
arr.max(axis = 0) or arr.max(axis = 1)
4. arr.imply(), arr.std(), arr.prod() # Returns imply std and product
-On this additionally we will discover column clever or row clever the identical manner
Integers randint() & New Generator default_rng()
1. np.random.randint(low=0, excessive=10, measurement=5) # or you possibly can give form like(3,2)
# => e.g. [3,7,1,8,0]2. rng = np.random.default_rng()
rng.random(5) # floats in [0,1)
rng.integers(5, size=3) # array([0, 1, 4], dtype=int64)
1. Distinctive objects
np.distinctive(arr)2. Transpose
arr.T # doesnt change the unique array
3. Flip
np.flip(arr) # full reverse
np.flip(arr, axis=0) # flip rows
np.flip(arr, axis=1) # flip columns
# Select explicit factor to filp
np.flip(arr[1]) np.flip(arr[:1] #for 2nd row / for 2nd column
4. Flatten vs. Ravel
Flatten- # new array This flattens the 2nd or 3d array into 1d!
a1= x.flatten()
a1[0]= 99
print(x)
print(a1)
'''[[1 2 3]
[4 5 6]
[7 8 9]]
[99 1 2 3 4 5 6 7]'''
Ravel- # works like view orignal array additionally will get modified!
a2= arr.ravel()
a2[0]= 98
print(arr)
print(a2)
'''[[98 2 3]
[4 5 6]
[7 8 9]]
[98 2 3 4 5 6 7 8 9]'''
📌 Tip: Use assist(np.function_name) in your pocket book to see full docs and parameters.
Thanks for sticking with me by means of this NumPy deep dive! You now have the basics to create, manipulate, and analyze arrays effectively — important groundwork for any ML venture.
🔜 What’s subsequent?
In our subsequent lesson, we’ll degree as much as pandas, the library constructed on NumPy for working with labeled, tabular information — good for actual‑world information evaluation and machine studying preparation.
See you there! 🚀Keep Tuned and Comply with in case you like :)!