Python numpy.delete()
Python numpy.delete()函数将返回一个新数组,并删除上述axis上的子数组。
语法:
numpy.delete(array, object, axis = None)
参数 :
array : [array_like]输入数组。
object : [int, array of ints]要删除的子数组。
axis : 我们想沿着这个轴来删除子数组。默认情况下,它的对象被应用于扁平化的数组。
返回 :
一个数组,其中的子数组被沿给定的轴线按照所述对象删除。
代码1:从1D数组中删除
# Python Program illustrating
# numpy.delete()
import numpy as geek
#Working on 1D
arr = geek.arange(5)
print("arr : \n", arr)
print("Shape : ", arr.shape)
# deletion from 1D array
object = 2
a = geek.delete(arr, object)
print("\ndeleteing {} from array : \n {}".format(object,a))
print("Shape : ", a.shape)
object = [1, 2]
b = geek.delete(arr, object)
print("\ndeleteing {} from array : \n {}".format(object,a))
print("Shape : ", a.shape)
输出 :
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,)
代码 2 :
# Python Program illustrating
# numpy.delete()
import numpy as geek
#Working on 1D
arr = geek.arange(12).reshape(3, 4)
print("arr : \n", arr)
print("Shape : ", arr.shape)
# deletion from 2D array
a = geek.delete(arr, 1, 0)
'''
[[ 0 1 2 3]
[ 4 5 6 7] -> deleted
[ 8 9 10 11]]
'''
print("\ndeleteing arr 2 times : \n", a)
print("Shape : ", a.shape)
# deletion from 2D array
a = geek.delete(arr, 1, 1)
'''
[[ 0 1* 2 3]
[ 4 5* 6 7]
[ 8 9* 10 11]]
^
Deletion
'''
print("\ndeleteing arr 2 times : \n", a)
print("Shape : ", a.shape)
输出 :
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)
代码3:使用布尔掩码执行的删除
# Python Program illustrating
# numpy.delete()
import numpy as geek
arr = geek.arange(5)
print("Original array : ", arr)
mask = geek.ones(len(arr), dtype=bool)
# Equivalent to np.delete(arr, [0,2,4], axis=0)
mask[[0,2]] = False
print("\nMask set as : ", mask)
result = arr[mask,...]
print("\nDeletion Using a Boolean Mask : ", result)
输出 :
Original array : [0 1 2 3 4]
Mask set as : [False True False True True]
Deletion Using a Boolean Mask : [1 3 4]
.