NumPy | delete method
Start your free 7-days trial now!
Numpy's delete(~)
method returns a new Numpy array with the specified values deleted.
Parameters
1. a
| array-like
The source array.
2. obj
| slice
or int
or array
of int
The subset of indices to delete along the specified axis.
3. axis
| int
| optional
The axis along which to perform the deletion. For 2D arrays, the allowed values and their meaning are:
Axis | Meaning |
---|---|
0 | Delete rows |
1 | Delete columns |
None | Delete from a flattened array |
By default, the axis=None
.
Return value
A new Numpy array with the specified values deleted.
Examples
Deleting from a 1D array
Consider the following 1D array:
a = np.array([3,4,5])a
array([3, 4, 5])
To delete the value at index 1:
np.delete(a, 1)
array([3, 5])
Deleting values from a flattened 2D array
Consider the following 2D array:
a = np.array([[4,5],[6,7]])a
array([[4, 5], [6, 7]])
Deleting a specific index
To delete a single index from the flattened version of the array:
np.delete(a, 2)
array([4, 5, 7])
Deleting multiple indices
To delete values at indices 0 and 2, pass in an array:
np.delete(a, [0,2])
array([5, 7])
Deleting rows from a 2D array
Suppose we have the following 2D array:
a = np.array([[4,5],[6,7]])a
array([[4, 5], [6, 7]])
Deleting a specific row
To delete row index 1:
np.delete(a, 1, axis=0)
array([[4, 5]])
Deleting multiple rows
To delete values at indices 0 and 2, pass in an array:
np.delete(a, [0,2])
array([5, 7])
Deleting columns from a 2D array
Deleting a specific column
Suppose we have the following 2D array:
a = np.array([[4,5],[6,7]])a
array([[4, 5], [6, 7]])
To delete column index 1:
np.delete(a, 1, axis=1)
array([[4], [6]])
Deleting multiple columns
Consider the following 2D array:
a = np.array([[1,2,3],[4,5,6],[7,8,9]])a
array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
To delete the columns at index 0 and 2:
np.delete(a, [0,2], axis=1)
array([[2], [5], [8]])