NumPy Tutorial

NumPy is a powerful Python library used for numerical computing. It provides support for arrays, matrices, and many mathematical functions to operate on these data structures efficiently. NumPy is widely used in scientific computing, data analysis, and machine learning.

Installing NumPy:

To install NumPy, you can use PIP:

pip install numpy

Creating Arrays:

NumPy's core data structure is the ndarray (N-dimensional array). You can create arrays in several ways:

Python
import numpy as np

# Create a 1D array
arr_1d = np.array([1, 2, 3, 4, 5])

# Create a 2D array
arr_2d = np.array([[1, 2, 3], [4, 5, 6]])

# Create an array with a range of values
arr_range = np.arange(0, 10, 2)

print(arr_1d)   # Output: [1 2 3 4 5]
print(arr_2d)   # Output: [[1 2 3]
               #          [4 5 6]]
print(arr_range)  # Output: [0 2 4 6 8]

Array Operations:

NumPy allows you to perform element-wise operations on arrays:

Python
import numpy as np

arr = np.array([1, 2, 3, 4, 5])

# Element-wise addition
arr_add = arr + 2

# Element-wise multiplication
arr_mul = arr * 2

print(arr_add)  # Output: [3 4 5 6 7]
print(arr_mul)  # Output: [2 4 6 8 10]

Array Indexing and Slicing:

NumPy arrays can be indexed and sliced similar to Python lists:

Python
import numpy as np

arr = np.array([10, 20, 30, 40, 50])

# Access an element by index
element = arr[2]

# Slice the array
sub_array = arr[1:4]

print(element)  # Output: 30
print(sub_array)  # Output: [20 30 40]

Array Reshaping:

NumPy allows you to change the shape of an array without changing its data:

Python
import numpy as np

arr = np.array([1, 2, 3, 4, 5, 6])

# Reshape 1D array to 2D array
reshaped_arr = arr.reshape((2, 3))

print(reshaped_arr)
# Output:
# [[1 2 3]
#  [4 5 6]]

Common NumPy Functions:

NumPy provides many built-in functions for common mathematical operations:

Python
import numpy as np

arr = np.array([1, 2, 3, 4, 5])

# Calculate the sum
sum_arr = np.sum(arr)

# Calculate the mean
mean_arr = np.mean(arr)

print(sum_arr)  # Output: 15
print(mean_arr)  # Output: 3.0

Working with Multi-dimensional Arrays:

NumPy supports operations on multi-dimensional arrays, which are useful for handling matrices:

Python
import numpy as np

matrix_1 = np.array([[1, 2], [3, 4]])
matrix_2 = np.array([[5, 6], [7, 8]])

# Matrix multiplication
result = np.dot(matrix_1, matrix_2)

print(result)
# Output:
# [[19 22]
#  [43 50]]

Broadcasting:

NumPy supports broadcasting, which allows you to perform operations on arrays of different shapes:

Python
import numpy as np

arr_1 = np.array([1, 2, 3])
arr_2 = np.array([[10], [20], [30]])

# Broadcasting
result = arr_1 + arr_2

print(result)
# Output:
# [[11 12 13]
#  [21 22 23]
#  [31 32 33]]

NumPy is a fundamental library for data science and scientific computing in Python. Its efficient array operations and mathematical capabilities make it indispensable for many tasks.