NumPy - Ndarray Object
NumPy - The ndarray Object
Section titled “NumPy - The ndarray Object”The cornerstone of the NumPy library is the N-dimensional array, represented by the ndarray class. An ndarray is essentially a versatile container designed to efficiently store and manipulate large datasets of homogeneous data (elements of the same type). Think of it as a grid of values, all of the same data type, indexed by a tuple of non-negative integers.
Key characteristics of an ndarray:
- Homogeneous Type: All elements must be of the same data type (e.g., all
int64or allfloat64). This allows for optimized storage and computation. - Fixed Size: The size (number of elements) of an array is fixed upon creation. Resizing usually involves creating a new array and copying data.
- Efficient Operations: Mathematical and logical operations can be performed on entire arrays (vectorization) without explicit Python loops, leveraging highly optimized C code.
- Multi-dimensional: Arrays can have multiple dimensions (axes), allowing representation of vectors (1D), matrices (2D), tensors (3D+).
Every ndarray has an associated data-type object (dtype) that describes the kind of data stored in the array (e.g., int32, float64, complex128). Each element in the array occupies a fixed-size block of memory determined by the dtype.
When you access a single element from an ndarray (e.g., my_array[0, 0]), you typically get a NumPy scalar object (like numpy.int64 or numpy.float64). These are distinct from standard Python types (int, float) but often behave similarly (‘duck typing’).
Creating ndarray Objects with numpy.array()
Section titled “Creating ndarray Objects with numpy.array()”The most fundamental way to create an ndarray is using the numpy.array() function. It converts various input data structures (like Python lists, tuples, or other array-like objects) into a NumPy array.
numpy.array(object, dtype=None, *, copy=True, order='K', subok=False, ndmin=0, like=None)Key parameters:
| Parameter | Description |
|---|---|
object | The input data, typically a nested sequence (list or tuple) or another array-like object. |
dtype | Optional. The desired data type for the array elements (e.g., np.float64, np.int32, np.bool_). If None, NumPy attempts to infer the best type. |
copy | Optional. If True (default), the function always creates a new copy of the input object. If False, a copy is only made if necessary (e.g., if the input is not already an ndarray of the correct dtype). |
order | Optional. Specifies memory layout: ‘C’ (row-major, C-style), ‘F’ (column-major, Fortran-style), ‘A’ (any, Fortran if input is Fortran contiguous), ‘K’ (keep layout of input, default). |
subok | Optional. If False (default), the returned array will be a base-class ndarray. If True, subclasses (like numpy.matrix) are passed through. |
ndmin | Optional. Specifies the minimum number of dimensions the resulting array should have. Axes will be prepended to the shape as needed. |
Let’s see some creation examples:
Example 1: Creating a 1D array from a list
Section titled “Example 1: Creating a 1D array from a list”import numpy as np
# Create from a list of integersa = np.array([1, 2, 3, 4])print(f"Array: {a}")print(f"Type: {type(a)}")print(f"Data Type (dtype): {a.dtype}")Output:
Array: [1 2 3 4]Type: <class 'numpy.ndarray'>Data Type (dtype): int64Example 2: Creating a 2D array (matrix)
Section titled “Example 2: Creating a 2D array (matrix)”import numpy as np
# Create from a list of listsb = np.array([[1.5, 2.0, 3.0], [4.0, 5.0, 6.0]])print(f"Array:\n{b}")print(f"Data Type (dtype): {b.dtype}")print(f"Shape: {b.shape}") # (rows, columns)print(f"Dimensions: {b.ndim}")Output:
Array:[[1.5 2. 3. ] [4. 5. 6. ]]Data Type (dtype): float64Shape: (2, 3)Dimensions: 2Example 3: Specifying minimum dimensions
Section titled “Example 3: Specifying minimum dimensions”import numpy as np
# Ensure the array is at least 2Dc = np.array([1, 2, 3], ndmin=2)print(f"Array (ndmin=2):\n{c}")print(f"Shape: {c.shape}")Output:
Array (ndmin=2):[[1 2 3]]Shape: (1, 3)Example 4: Specifying the data type
Section titled “Example 4: Specifying the data type”import numpy as np
# Create an array with complex numbersd = np.array([1, 2, 3], dtype=np.complex128)print(f"Array (complex): {d}")print(f"Data Type (dtype): {d.dtype}")Output:
Array (complex): [1.+0.j 2.+0.j 3.+0.j]Data Type (dtype): complex128Internally, the ndarray manages a contiguous block of computer memory. An indexing scheme maps element indices (like [1, 2]) to specific locations within this memory block. The order parameter (‘C’ or ‘F’) influences how multi-dimensional array elements are arranged in this linear memory block.
Explore more about the ndarray in the official ndarray documentation and the numpy.array function documentation.