NumPy Introduction
NumPy is a powerful library for numerical computing in Python. It provides support for arrays, matrices, and many mathematical functions to operate on these data structures.
Installing NumPy
You can install NumPy using pip:
pip install numpy
Creating NumPy Arrays
NumPy arrays are the central data structure of the NumPy library. You can create NumPy arrays using the numpy.array()
function.
Example
The following code demonstrates how to create a simple NumPy array:
import numpy as np
# Creating a NumPy array
arr = np.array([1, 2, 3, 4, 5])
print(arr)
Output:
[1 2 3 4 5]
Array Operations
NumPy supports a variety of operations on arrays such as addition, subtraction, multiplication, and division.
Example
The following code demonstrates basic array operations:
import numpy as np
# Creating two NumPy arrays
arr1 = np.array([1, 2, 3])
arr2 = np.array([4, 5, 6])
# Array addition
add_result = np.add(arr1, arr2)
print("Addition:", add_result)
# Array subtraction
sub_result = np.subtract(arr1, arr2)
print("Subtraction:", sub_result)
# Array multiplication
mul_result = np.multiply(arr1, arr2)
print("Multiplication:", mul_result)
# Array division
div_result = np.divide(arr1, arr2)
print("Division:", div_result)
Output:
Addition: [5 7 9]
Subtraction: [-3 -3 -3]
Multiplication: [ 4 10 18]
Division: [0.25 0.4 0.5 ]
Array Slicing
You can access and modify parts of an array using slicing.
Example
The following code demonstrates how to slice a NumPy array:
import numpy as np
# Creating a NumPy array
arr = np.array([10, 20, 30, 40, 50])
# Slicing the array
slice_arr = arr[1:4]
print(slice_arr)
Output:
[20 30 40]
Array Shape
NumPy arrays have a shape attribute that indicates the number of elements along each dimension.
Example
The following code demonstrates how to check the shape of a NumPy array:
import numpy as np
# Creating a 2D NumPy array
arr = np.array([[1, 2, 3], [4, 5, 6]])
# Checking the shape of the array
print(arr.shape)
Output:
(2, 3)
Array Reshaping
You can reshape an array using the reshape()
method.
Example
The following code demonstrates how to reshape a NumPy array:
import numpy as np
# Creating a NumPy array
arr = np.array([1, 2, 3, 4, 5, 6])
# Reshaping the array
reshaped_arr = arr.reshape(2, 3)
print(reshaped_arr)
Output:
[[1 2 3]
[4 5 6]]
Conclusion
NumPy is a fundamental package for scientific computing in Python, providing powerful tools to handle and operate on arrays. This chapter covered the basics of NumPy, including array creation, operations, slicing, shaping, and reshaping.