delete() constructs a brand-new array containing everything except the specified indices, a single index, a list of indices, or a slice, along the given axis, since NumPy arrays can't shrink in place any more than they can grow in place. Without an axis argument, the array is flattened first and elements are removed from that flattened sequence, which is rarely what's wanted for multi-dimensional data, so axis should almost always be specified explicitly when working with anything beyond a 1D array.
1Understanding np.delete()
delete() constructs a brand-new array containing everything except the specified indices, a single index, a list of indices, or a slice, along the given axis, since NumPy arrays can't shrink in place any more than they can grow in place. Without an axis argument, the array is flattened first and elements are removed from that flattened sequence, which is rarely what's wanted for multi-dimensional data, so axis should almost always be specified explicitly when working with anything beyond a 1D array.
Always specify the axis argument explicitly when calling np.delete() on a multi-dimensional array — omitting it flattens the array first, which almost never produces the result you actually want for 2D+ data.
import numpy as np
arr = np.array([1, 2, 3, 4, 5])
result = np.delete(arr, 2)
print(result)2Practical Example
Here is a real-world application of np.delete() showing how it is used in production NumPy code.
import numpy as np
matrix = np.array([[1, 2], [3, 4], [5, 6]])
result = np.delete(matrix, 1, axis=0)
print(result)3Best Practices
Follow these guidelines when working with np.delete():
1. Always pass axis explicitly for 2D+ arrays, since the default flattens the array first, which is rarely the intended behavior
2. Use boolean indexing or a boolean mask instead of np.delete() when the condition for removal is computed dynamically, rather than a known fixed set of indices
3. Remember np.delete() always returns a new array, leaving the original untouched, unlike Python's list del statement which modifies in place
Tip: Always specify the axis argument explicitly when calling np.delete() on a multi-dimensional array — omitting it flattens the array first, which almost never produces the result you actually want for 2D+ data.
import numpy as np
arr = np.array([1, 2, 3, 4, 5])
result = np.delete(arr, 2)
print(result)