numpy.delete() in Python (original) (raw)
Last Updated : 09 Aug, 2022
The numpy.delete() function returns a new array with the deletion of sub-arrays along with the mentioned axis.
Syntax:
numpy.delete(array, object, axis = None)
Parameters :
array : [array_like]Input array.
object : [int, array of ints]Sub-array to delete
axis : Axis along which we want to delete sub-arrays. By default, it object is applied to
flattened array
Return :
An array with sub-array being deleted as per the mentioned object along a given axis.
Code 1 : Deletion from 1D array
Python
Output :
arr : [0 1 2 3 4] Shape : (5,)
deleting arr 2 times : [0 1 3 4] Shape : (4,)
deleting arr 3 times : [0 3 4] Shape : (4,)
Code 2 :
Python
import
numpy as geek
arr
=
geek.arange(
12
).reshape(
3
,
4
)
print
(
"arr : \n"
, arr)
print
(
"Shape : "
, arr.shape)
a
=
geek.delete(arr,
1
,
0
)
print
(
"\ndeleteing arr 2 times : \n"
, a)
print
(
"Shape : "
, a.shape)
a
=
geek.delete(arr,
1
,
1
)
print
(
"\ndeleteing arr 2 times : \n"
, a)
print
(
"Shape : "
, a.shape)
Output :
arr : [[ 0 1 2 3] [ 4 5 6 7] [ 8 9 10 11]] Shape : (3, 4)
deleting arr 2 times : [[ 0 1 2 3] [ 8 9 10 11]] Shape : (2, 4)
deleting arr 2 times : [[ 0 2 3] [ 4 6 7] [ 8 10 11]] Shape : (3, 3)
deleting arr 3 times : [ 0 3 4 5 6 7 8 9 10 11] Shape : (3, 3)
Code 3: Deletion performed using Boolean Mask
Python
import
numpy as geek
arr
=
geek.arange(
5
)
print
(
"Original array : "
, arr)
mask
=
geek.ones(
len
(arr), dtype
=
bool
)
mask[[
0
,
2
]]
=
False
print
(
"\nMask set as : "
, mask)
result
=
arr[mask,...]
print
(
"\nDeletion Using a Boolean Mask : "
, result)
Output :
Original array : [0 1 2 3 4]
Mask set as : [False True False True True]
Deletion Using a Boolean Mask : [1 3 4]
References :
https://docs.scipy.org/doc/numpy/reference/generated/numpy.delete.html
Note :
These codes won’t run on online IDE’s. Please run them on your systems to explore the working
.