Overview of NumPy Framework
NumPy (Numerical Python) is a fundamental package for numerical computing in Python. It provides support for large arrays and matrices, along with mathematical functions to manipulate these data structures efficiently.
Installing NumPy
To start using NumPy, install it using pip:
pip install numpy
Creating NumPy Arrays
NumPy arrays can be created using the array function:
import numpy as np
# Creating a 1D array
arr = np.array([10, 20, 30, 40, 50])
print(arr)
Output:
[10 20 30 40 50]
Array Operations
NumPy supports various operations on arrays:
a = np.array([2, 4, 6])
b = np.array([1, 3, 5])
print(a + b) # Addition
print(a - b) # Subtraction
print(a * b) # Multiplication
print(a / b) # Division
Output:
[3 7 11]
[1 1 1]
[ 2 12 30]
[2. 1.33333333 1.2]
Array Shape and Reshaping
You can check and modify the shape of an array:
c = np.array([[10, 20, 30], [40, 50, 60]])
print(c.shape) # Output: (2, 3)
d = c.reshape(3, 2)
print(d)
Output:
(2, 3)
[[10 20]
[30 40]
[50 60]]
Generating Special Arrays
NumPy provides functions for creating specific types of arrays:
print(np.zeros((3, 3))) # 3x3 array of zeros
print(np.ones((2, 2))) # 2x2 array of ones
print(np.eye(4)) # 4x4 identity matrix
print(np.arange(5, 25, 5)) # Array with step size 5
Output:
[[0. 0. 0.]
[0. 0. 0.]
[0. 0. 0.]]
[[1. 1.]
[1. 1.]]
[[1. 0. 0. 0.]
[0. 1. 0. 0.]
[0. 0. 1. 0.]
[0. 0. 0. 1.]]
[ 5 10 15 20]
Conclusion
NumPy is an essential library for numerical computations in Python. Its array manipulation capabilities make it an efficient tool for scientific computing and data analysis.