NumPy, short for Numerical Python, is a powerful library in Python that provides support for large, multi-dimensional arrays and matrices.
ndarray
The NumPy ndarray
(N-dimensional array) is the core class of NumPy, designed for fast and efficient numerical computations. It provides a container for multi-dimensional homogeneous data, meaning that all elements in an ndarray
must be of the same data type.
Unlike Python lists, which can store different types of data and have dynamic sizes, NumPy arrays are fixed in size and have a uniform data type, making them significantly faster for mathematical operations.
Key Features of NumPy ndarray
- Multi-dimensional Structure – Supports 1D, 2D, and higher-dimensional arrays.
- Efficient Memory Usage – Optimized for storing large datasets with minimal memory overhead.
- Fast Computation – Performs element-wise operations efficiently using vectorization.
- Broadcasting – Allows operations on arrays of different shapes without explicit looping.
- Integration with Other Libraries – Compatible with SciPy, Pandas, Matplotlib, and other scientific computing libraries.
ndarray attributes
- ndarray.T
T
- Returns a transposed view of the array, swapping rows and columns.
- ndarray.data
data
- Python buffer object pointing to the start of the array’s data, useful for low-level memory operations.
- ndarray.dtype
dtype
- Represents the data type of array elements, specifying how the elements are stored in memory.
- ndarray.flags
flags
- A dictionary-like object providing details about the memory layout and mutability of the array.
- ndarray.flat
flat
- A 1D iterator over the elements of the array, allowing easy traversal and modifications.
- ndarray.imag
imag
- Returns the imaginary component of each element in the array, relevant for complex numbers.
- ndarray.real
real
- Returns the real component of each element in the array, separating complex numbers into their real part.
- ndarray.size
size
- Returns the total number of elements in the array.
- ndarray.itemsize
itemsize
- Gives the size (in bytes) of each element in the array.
- ndarray.nbytes
nbytes
- Returns the total memory consumption of the array in bytes.
- ndarray.ndim
ndim
- Returns the number of dimensions (axes) of the array.
- ndarray.shape
shape
- Returns a tuple representing the dimensions of the array.
- ndarray.strides
strides
- Returns a tuple indicating the number of bytes to step in each dimension when traversing the array.
- ndarray.ctypes
ctypes
- Provides an interface for interacting with the array using the
ctypes
module. - ndarray.base
base
- References the base object if the array memory is shared with another object.
ndarray methods
- ndarray.all()
all([axis, out, keepdims, where])
- Returns
True
if all elements in the array evaluate toTrue
along the specified axis. Useful for checking if an entire array or subarray meets a condition. - ndarray.any()
any([axis, out, keepdims, where])
- Returns
True
if at least one element in the array evaluates toTrue
. Can be used to check for the presence of nonzero values. - ndarray.argmax()
argmax([axis, out, keepdims])
- Returns the indices of the maximum values along a specified axis. Helps in identifying the position of the highest value in an array.
- ndarray.argmin()
argmin([axis, out, keepdims])
- Returns the indices of the minimum values along the specified axis. Useful for finding the location of the smallest value in an array.
- ndarray.argpartition()
argpartition(kth[, axis, kind, order])
- Returns the indices that would partition the array such that the element at the
kth
position is in its sorted position, while elements before and after are not fully sorted. - ndarray.argsort()
argsort([axis, kind, order])
- Returns the indices that would sort the array along the specified axis. The indices can be used for indirect sorting.
- ndarray.astype()
astype(dtype[, order, casting, subok, copy])
- Returns a copy of the array cast to a specified data type. Can be used to convert arrays between different numerical types.
- ndarray.byteswap()
byteswap([inplace])
- Swaps the byte order of array elements, useful when working with data that has a different endianness than the system’s native format.
- ndarray.choose()
choose(choices[, out, mode])
- Constructs a new array by selecting elements from a list of arrays using an index array. Useful for conditional selection from multiple sources.
- ndarray.clip()
clip([min, max, out])
- Limits the values in an array to a specified range by replacing elements below
min
withmin
and those abovemax
withmax
. - ndarray.compress()
compress(condition[, axis, out])
- Selects elements from an array along the specified axis based on a boolean condition array.
- ndarray.conj()
conj()
- Returns the complex conjugate of all elements in the array. Useful for complex number operations.
- ndarray.conjugate()
conjugate()
- Computes the complex conjugate element-wise, equivalent to
conj()
. - ndarray.copy()
copy([order])
- Creates and returns a copy of the array. The
order
parameter allows control over memory layout. - ndarray.cumprod()
cumprod([axis, dtype, out])
- Computes the cumulative product of elements along the specified axis, multiplying each element by the previous one iteratively.
- ndarray.cumsum()
cumsum([axis, dtype, out])
- Computes the cumulative sum of array elements along the specified axis, adding each element to the sum of previous elements.
- ndarray.diagonal()
diagonal([offset, axis1, axis2])
- Returns a view of the specified diagonals of a 2D or higher-dimensional array.
- ndarray.dump()
dump(file)
- Saves a binary pickle representation of the array to a specified file for later retrieval.
- ndarray.dumps()
dumps()
- Serializes the array into a string representation using pickle.
- ndarray.fill()
fill(value)
- Fills the entire array with a specified scalar value, modifying it in place.
- ndarray.flatten()
flatten([order])
- Returns a new 1D array that is a flattened version of the original array, preserving order if specified.
- ndarray.getfield()
getfield(dtype[, offset])
- Extracts a field from the array with a specified data type, optionally with an offset.
- ndarray.item()
item(*args)
- Returns a standard Python scalar value from the array at a specified position.
- ndarray.max()
max([axis, out, keepdims, initial, where])
- Finds the maximum value along the specified axis, considering only elements that meet an optional condition.
- ndarray.mean()
mean([axis, dtype, out, keepdims, where])
- Computes the arithmetic mean (average) of the array elements along the specified axis.
- ndarray.min()
min([axis, out, keepdims, initial, where])
- Finds the minimum value along the specified axis, optionally ignoring certain values.
- ndarray.nonzero()
nonzero()
- Returns the indices of all non-zero elements in the array, useful for filtering.
- ndarray.partition()
partition(kth[, axis, kind, order])
- Partially sorts the array such that the element at the
kth
position is in its final sorted position, with smaller elements before and larger elements after. - ndarray.prod()
prod([axis, dtype, out, keepdims, initial, ...])
- Computes the product of array elements along the specified axis. Useful for cumulative multiplication operations.
- ndarray.put()
put(indices, values[, mode])
- Replaces elements in the flattened array at specific indices with new values.
- ndarray.ravel()
ravel([order])
- Returns a flattened 1D view of the array. Can preserve memory layout order if specified.
- ndarray.repeat()
repeat(repeats[, axis])
- Repeats each element of the array along the given axis.
- ndarray.reshape()
reshape(shape, /, *[, order, copy])
- Returns a new array with the same data arranged in the specified shape.
- ndarray.resize()
resize(new_shape[, refcheck])
- Changes the shape and size of the array in-place, altering its data layout.
- ndarray.round()
round([decimals, out])
- Rounds each element in the array to the specified number of decimal places.
- ndarray.searchsorted()
searchsorted(v[, side, sorter])
- Finds the indices where elements should be inserted in the array to maintain order.
- ndarray.setfield()
setfield(val, dtype[, offset])
- Assigns a value into a field within the array as defined by a given data type.
- ndarray.setflags()
setflags([write, align, uic])
- Modifies array memory layout flags, controlling writeability and alignment.
- ndarray.sort()
sort([axis, kind, order])
- Sorts the array in-place along the specified axis using different sorting algorithms.
- ndarray.squeeze()
squeeze([axis])
- Removes single-dimensional axes from the array, making it more compact.
- ndarray.std()
std([axis, dtype, out, ddof, keepdims, where])
- Computes the standard deviation of array elements along the specified axis. Measures data dispersion from the mean.
- ndarray.sum()
sum([axis, dtype, out, keepdims, initial, where])
- Computes the sum of array elements along the specified axis. Supports additional options like initial value and conditional summation.
- ndarray.swapaxes()
swapaxes(axis1, axis2)
- Returns a view of the array with two specified axes swapped.
- ndarray.take()
take(indices[, axis, out, mode])
- Returns a new array formed by selecting elements from the original array based on specified indices.
- ndarray.tobytes()
tobytes([order])
- Converts the array into a Python bytes object containing the raw data.
- ndarray.tofile()
tofile(fid[, sep, format])
- Writes the array to a file in text or binary format, with optional separators and formatting.
- ndarray.tolist()
tolist()
- Converts the array into a nested list of Python scalars, matching the array’s dimensional structure.
- ndarray.tostring()
tostring([order])
- Deprecated alias for
tobytes()
, providing identical functionality. - ndarray.trace()
trace([offset, axis1, axis2, dtype, out])
- Computes the sum along the main diagonal (or an offset diagonal) of a 2D array.
- ndarray.transpose()
transpose(*axes)
- Returns a view of the array with reordered axes, useful for reshaping multi-dimensional data.
- ndarray.var()
var([axis, dtype, out, ddof, keepdims, where])
- Computes the variance of array elements along a specified axis, measuring data spread.
- ndarray.view()
view([dtype][, type])
- Returns a new view of the array with the same underlying data but a different dtype or type.