NumPy Overview
NumPy (Numerical Python) serves as the foundational library for scientific computing in Python. It provides extensive capabilities for statistical analysis, random number generation, and numerical operations. The core data structure is the multidimensional array (ndarray), which enables efficient handling of n-dimensional arrays and matrix operations. NumPy processes ndarray objects using vectorization, significantly improving computational performance compared to traditional Python loops.
Checking NumPy Version
import numpy as np
print(np.__version__)
The ndarray Object
The N-dimensional array (ndarray) is a collection of elements of the same type, indexed starting from zero. Each element occupies an identical amount of memory, enabling efficient bulk operations and memory access patterns.
Array Creation
Using array()
numpy.array(object, dtype=None, copy=True, order=None, subok=False, ndmin=0)
Parameters:
- object: Array or nested sequence
- dtype: Data type of array elements (optional)
- copy: Whether to copy the object (optional)
- order: Array layout - 'C' for row-major, 'F' for column-major, 'A' for any
- subok: Whether to return a subclass array
- ndmin: Minimum number of dimensions for the output array
Example:
import numpy as np
data = np.array([1, 2, 3], dtype=float, ndmin=2)
print(data)
Output:
[[1. 2. 3.]]
NumPy Array Attributes
NumPy arrays have several importent attributes:
- ndarray.ndim: Number of dimensions (axes)
- ndarray.shape: Tuple indicating array dimensions (rows × columns)
- ndarray.size: Total number of elements
- ndarray.dtype: Element data type
- ndarray.itemsize: Size of each element in bytes
- ndarray.flags: Memory layout information
- ndarray.real: Real component of elements
- ndarrray.imag: Imaginary component of elements
Example:
import numpy as np
matrix = np.array([[1, 2, 3], [4, 5, 6]])
print(f"Shape: {matrix.shape}")
print(f"Size: {matrix.size}")
print(f"Data type: {matrix.dtype}")
Output:
Shape: (2, 3)
Size: 6
Data type: int32
Creating Arrays from Existing Data
numpy.asarray
The asarray function converts input data into an ndarray. It accepts fewer parameters than array().
numpy.asarray(a, dtype=None, order=None)
Parameters:
- a: Input data in any form - list, tuple, nested sequences, or multidimensional array
- dtype: Optional data type
- order: Memory layout - 'C' (row-major) or 'F' (column-major)
Example:
import numpy as np
source = [(1, 2, 3), (4, 5, 6)]
print(f"Source type: {type(source)}")
result = np.asarray(source)
print(f"Array type: {type(result)}")
Output:
Source type: <class 'list'>
Array type: <class 'numpy.ndarray'>
Creating Arrays from Numerical Ranges
numpy.arange
The arange function generates arrays with sequential values based on specified ranges.
numpy.arange(start, stop, step, dtype)
Parameters:
- start: Starting value (default 0)
- stop: End value (exclusive)
- step: Increment between values (default 1)
- dtype: Output data type
Example:
import numpy as np
sequence = np.arange(10, 20, 2)
print(sequence)
Output:
[10 12 14 16 18]
Array Slicing
NumPy arrays support indexing and slicing similar to Python lists. Access elements using zero-based indices or extract portions using slice notation with start, stop, and step parameters.
import numpy as np
values = np.arange(10)
subset = values[2:7:2]
print(subset)
Output:
[2 4 6]
This extracts elements from index 2 through index 6, stepping by 2.