Numpy
Numpy
What is NumPy?
NumPy is a powerful Python library used for:
Numerical computations
Multi-dimensional arrays
Matrix operations
Scientific computing
Machine Learning and AI applications
It is faster than normal Python lists because it uses optimized C-based implementations.
a = [Link]([1, 2, 3, 4])
print(a)
Output:
[1 2 3 4]
2D Array:
b = [Link]([[1,2,3],
[4,5,6]])
print(b)
2. Shape of Array
Definition
Shape tells:
Number of rows
Number of columns
Dimensions of array
import numpy as np
a = [Link]([[1,2,3],
[4,5,6]])
print([Link])
Output:
(2, 3)
Meaning:
2 rows
3 columns
3. Slicing in NumPy
Definition
Slicing extracts specific portions of an array.
Syntax:
array[start:end]
1D Slicing
import numpy as np
a = [Link]([10,20,30,40,50])
print(a[1:4])
Output:
[20 30 40]
2D Slicing
import numpy as np
a = [Link]([[1,2,3],
[4,5,6],
[7,8,9]])
print(a[0:2, 1:3])
Output:
[[2 3]
[5 6]]
Explanation:
Rows: 0 to 1
Columns: 1 to 2
4. Masking in NumPy
Definition
Masking means filtering elements using conditions.
import numpy as np
a = [Link]([10,20,30,40,50])
mask = a > 25
print(mask)
print(a[mask])
Output:
[False False True True True]
[30 40 50]
Explanation:
5. Broadcasting
Definition
Broadcasting allows NumPy to perform operations on arrays of different shapes.
Example:
import numpy as np
a = [Link]([1,2,3])
print(a + 5)
Output:
[6 7 8]
Here:
a = [Link]([[1],[2],[3]])
b = [Link]([10,20,30])
print(a + b)
Output:
[[11 21 31]
[12 22 32]
[13 23 33]]
6. dtype in NumPy
Definition
dtype specifies the data type of array elements.
Example:
import numpy as np
a = [Link]([1,2,3])
print([Link])
Output:
int64
Changing dtype
import numpy as np
a = [Link]([1,2,3], dtype=float)
print(a)
print([Link])
Output:
[1. 2. 3.]
float64
Complete Example
import numpy as np
a = [Link]([[1,2,3],
[4,5,6]])
print("Shape:", [Link])
print("Slice:")
print(a[:,1:3])
print("Masking:")
print(a[a > 3])
print("Broadcasting:")
print(a + 10)
print("Datatype:", [Link])
Output:
Shape: (2, 3)
Slice:
[[2 3]
[5 6]]
Masking:
[4 5 6]
Broadcasting:
[[11 12 13]
[14 15 16]]
Datatype: int64