Numpy Tutorial in Python
NumPy Tutorial in Python
NumPy (Numerical Python) is a powerful library for numerical computing in Python. It provides support for large, multi-dimensional arrays and matrices, along with a collection of mathematical functions to operate on these arrays. NumPy is widely used in scientific computing, data analysis, and machine learning.
1. Installation
To install NumPy, you can use the following command:
pip install numpy2. Importing NumPy
import numpy as npThis imports NumPy and gives it the alias np, which is the common convention.
3. Creating NumPy Arrays
NumPy arrays are the core data structure in NumPy. They are more efficient than Python lists and provide vectorized operations.
a. Creating Arrays from Lists
You can create a NumPy array from a Python list using np.array().
import numpy as np# Creating a 1D arrayarr = np.array([1, 2, 3, 4])print(arr) # Output: [1 2 3 4]# Creating a 2D arrayarr_2d = np.array([[1, 2, 3], [4, 5, 6]])print(arr_2d)# Output:# [[1 2 3]# [4 5 6]]b. Creating Arrays with Zeros, Ones, and Random Values
np.zeros(): Creates an array of zeros.np.ones(): Creates an array of ones.np.random.rand(): Creates an array of random numbers between 0 and 1.
# Array of zeroszeros = np.zeros((3, 3)) # 3x3 arrayprint(zeros)# Array of onesones = np.ones((2, 4)) # 2x4 arrayprint(ones)# Array with random valuesrandom_vals = np.random.rand(3, 3) # 3x3 array with random valuesprint(random_vals)4. Array Properties
You can access various properties of NumPy arrays:
arr = np.array([1, 2, 3, 4, 5])# Shape of the array (dimensions)print(arr.shape) # Output: (5,)# Number of dimensionsprint(arr.ndim) # Output: 1# Size of the array (total number of elements)print(arr.size) # Output: 5# Data type of the arrayprint(arr.dtype) # Output: int64 (or int32, depending on your system)For 2D arrays:
arr_2d = np.array([[1, 2, 3], [4, 5, 6]])# Shape of the 2D arrayprint(arr_2d.shape) # Output: (2, 3)5. Array Indexing and Slicing
NumPy arrays can be indexed and sliced just like Python lists, but with more powerful options for multi-dimensional arrays.
a. Indexing
arr = np.array([10, 20, 30, 40, 50])# Accessing individual elementsprint(arr[0]) # Output: 10print(arr[3]) # Output: 40b. Slicing
# Slicing from index 1 to 3print(arr[1:4]) # Output: [20 30 40]c. Slicing for 2D arrays
arr_2d = np.array([[1, 2, 3], [4, 5, 6]])# Accessing a specific rowprint(arr_2d[1]) # Output: [4 5 6]# Slicing the 2D arrayprint(arr_2d[:, 1:3]) # Output: [[2 3] [5 6]]6. Array Operations
NumPy arrays support a wide range of mathematical operations, and these operations are performed element-wise.
a. Arithmetic Operations
arr1 = np.array([1, 2, 3])arr2 = np.array([4, 5, 6])# Additionprint(arr1 + arr2) # Output: [5 7 9]# Subtractionprint(arr1 - arr2) # Output: [-3 -3 -3]# Multiplicationprint(arr1 * arr2) # Output: [4 10 18]# Divisionprint(arr1 / arr2) # Output: [0.25 0.4 0.5]# Exponentiationprint(arr1 ** 2) # Output: [1 4 9]b. Universal Functions (ufuncs)
NumPy provides universal functions (ufuncs) to perform element-wise operations on arrays.
arr = np.array([1, 4, 9])# Square rootprint(np.sqrt(arr)) # Output: [1. 2. 3.]# Exponentialprint(np.exp(arr)) # Output: [2.71828183e+00 5.45981500e+01 8.10308393e+03]# Logarithmprint(np.log(arr)) # Output: [0. 1.38629436 2.19722458]7. Broadcasting
Broadcasting is a powerful feature in NumPy that allows you to perform operations on arrays of different shapes. When operating on arrays, NumPy compares the shapes of the arrays element-wise and "broadcasts" the smaller array across the larger one.
Example:
arr1 = np.array([1, 2, 3])arr2 = np.array([10])# Broadcasting: arr2 is broadcasted to match the shape of arr1print(arr1 + arr2) # Output: [11 12 13]8. Reshaping Arrays
You can change the shape of a NumPy array using the reshape() method.
arr = np.array([1, 2, 3, 4, 5, 6])# Reshaping to 2x3 matrixarr_reshaped = arr.reshape((2, 3))print(arr_reshaped)# Output:# [[1 2 3]# [4 5 6]]9. Statistical Operations
NumPy provides a variety of functions to calculate statistics.
arr = np.array([1, 2, 3, 4, 5])# Meanprint(np.mean(arr)) # Output: 3.0# Medianprint(np.median(arr)) # Output: 3.0# Standard Deviationprint(np.std(arr)) # Output: 1.4142135623730951# Sumprint(np.sum(arr)) # Output: 1510. Linear Algebra in NumPy
NumPy also provides functions for linear algebra operations.
# Dot productarr1 = np.array([1, 2])arr2 = np.array([3, 4])print(np.dot(arr1, arr2)) # Output: 11 (1*3 + 2*4)# Matrix multiplicationarr_2d_1 = np.array([[1, 2], [3, 4]])arr_2d_2 = np.array([[5, 6], [7, 8]])print(np.matmul(arr_2d_1, arr_2d_2))# Output:# [[19 22]# [43 50]]11. Saving and Loading Arrays
You can save and load NumPy arrays to/from files using the np.save() and np.load() functions.
Saving an array:
arr = np.array([1, 2, 3, 4])np.save('my_array.npy', arr)Loading an array:
loaded_arr = np.load('my_array.npy')print(loaded_arr) # Output: [1 2 3 4]12. Summary of Key Functions in NumPy
| Function | Description |
|---|---|
np.array() | Create an array from a list or other sequence. |
np.zeros() | Create an array of zeros. |
np.ones() | Create an array of ones. |
np.random.rand() | Create an array with random values. |
np.mean() | Calculate the mean of an array. |
np.median() | Calculate the median of an array. |
np.std() | Calculate the standard deviation of an array. |
np.dot() | Compute the dot product of two arrays. |
np.reshape() | Change the shape of an array. |
Conclusion
NumPy is a powerful and versatile library for numerical computing in Python. Whether you're working with simple arrays, performing complex mathematical operations, or handling multi-dimensional matrices, NumPy provides all the tools you need for efficient computation.