Python Libraries: NumPy (Basics)
What is NumPy?
NumPy, which stands for Numerical Python, is a powerful library in Python for numerical computing. 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, machine learning, and other domains where numerical operations are required.
NumPy is built on top of the C programming language, which makes it fast and efficient for numerical computations. It provides an easy-to-use interface for creating, manipulating, and performing operations on arrays, making it an essential tool for numerical computing in Python.
Installing NumPy
NumPy is not included in the standard Python distribution, so you need to install it separately. You can install NumPy using the pip
package manager, which is the standard package manager for Python. To install NumPy, you can use the following command:
pip install numpy
This command will download and install the NumPy library on your system, making it available for use in your Python programs.
Importing NumPy
To use NumPy in your Python programs, you need to import the NumPy library. You can import NumPy using the following import statement:
import numpy as np
In this statement, numpy
is the name of the library, and np
is an alias that you can use to refer to the library in your code. By convention, np
is the standard alias used for NumPy, and you will see it used in most NumPy code examples.
Creating NumPy Arrays
One of the key features of NumPy is its support for multi-dimensional arrays. You can create NumPy arrays using the np.array()
function, which takes a Python list as input and converts it into a NumPy array. Here’s an example of creating a NumPy array:
import numpy as np
# Create a 1D NumPy array
arr1d = np.array([1, 2, 3, 4, 5])
print("1D NumPy array:")
print(arr1d)
# Create a 2D NumPy array
arr2d = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
print("2D NumPy array:")
print(arr2d)
In this example, we create a 1D NumPy array arr1d
and a 2D NumPy array arr2d
using the np.array()
function. The arrays are printed to the console using the print()
function.
NumPy Array Attributes
NumPy arrays have several attributes that provide information about the array, such as its shape, size, data type, and more. Here are some common attributes of NumPy arrays:
Attribute | Description |
---|---|
ndim | Number of dimensions (axes) of the array. |
shape | Tuple of integers indicating the size of the array in each dimension. |
size | Total number of elements in the array. |
dtype | Data type of the elements in the array. |
itemsize | Size in bytes of each element in the array. |
nbytes | Total size in bytes of the array. |
strides | Tuple of bytes to step in each dimension when traversing the array. |
flags | Information about the memory layout of the array. |
real | Real part of the array (for complex arrays). |
imag | Imaginary part of the array (for complex arrays). |
flat | 1D iterator over the array. |
Basic Array Operations
NumPy provides a wide range of mathematical functions and operations that can be performed on NumPy arrays. Here are some common operations that you can perform on NumPy arrays:
- Element-wise Operations: Perform arithmetic operations on corresponding elements of two arrays.
- Array Broadcasting: Perform operations on arrays of different shapes by broadcasting the smaller array to match the shape of the larger array.
- Aggregation Functions: Calculate statistics such as mean, median, sum, min, max, etc., on arrays.
- Indexing and Slicing: Access and modify elements of an array using indexing and slicing operations.
- Reshaping and Resizing: Change the shape and size of an array using the
reshape()
andresize()
functions. - Stacking and Splitting: Combine multiple arrays into a single array or split a single array into multiple arrays.
- Sorting and Searching: Sort elements of an array and search for specific elements in an array.
- Linear Algebra Operations: Perform matrix operations such as matrix multiplication, inversion, and decomposition.
- Random Number Generation: Generate random numbers and arrays using NumPy’s random number functions.
Example: Element-wise Operations
Element-wise operations are operations that are performed on corresponding elements of two arrays. For example, you can add, subtract, multiply, or divide two arrays element-wise. Here’s an example of performing element-wise addition on two NumPy arrays:
import numpy as np
# Create two NumPy arrays
arr1 = np.array([1, 2, 3, 4, 5])
arr2 = np.array([6, 7, 8, 9, 10])
# Perform element-wise addition
result = arr1 + arr2
print("Array 1:")
print(arr1)
print("Array 2:")
print(arr2)
print("Result of element-wise addition:")
print(result) # Output: [ 7 9 11 13 15]
In this example, we create two NumPy arrays arr1
and arr2
and perform element-wise addition using the +
operator. The result of the addition operation is stored in the result
array and printed to the console.