NumPy (Numerical Python) is a powerful library in Python used 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 more, due to its efficiency and ease of use.
Here's a breakdown of key concepts and features of NumPy:
The core feature of NumPy is the ndarray
, which is a fast and memory-efficient multi-dimensional array object. It can represent data in various dimensions:
Example of creating an ndarray:
import numpy as np
# 1D array (vector)
arr_1d = np.array([1, 2, 3, 4])
# 2D array (matrix)
arr_2d = np.array([[1, 2], [3, 4]])
# 3D array
arr_3d = np.array([[[1], [2]], [[3], [4]]])
Each ndarray
object has various attributes:
ndarray.shape
: Shape of the array (i.e., the number of elements along each axis).ndarray.ndim
: The number of dimensions (axes).ndarray.size
: The total number of elements.ndarray.dtype
: Data type of the elements.Example:
arr = np.array([[1, 2, 3], [4, 5, 6]])
print(arr.shape) # Output: (2, 3)
print(arr.ndim) # Output: 2
print(arr.size) # Output: 6
print(arr.dtype) # Output: int64 (or int32 depending on the platform)