NumPy delete() 函数



NumPy 的delete()函数用于返回一个新的数组,其中从输入数组中删除了指定的子数组。如果未提供axis参数,则在删除之前会先将输入数组展平。

此函数可用于从数组中删除元素、行或列。

语法

以下是 NumPy delete() 函数的语法:

Numpy.delete(arr, obj, axis)

参数

以下是 NumPy delete() 函数的参数:

  • arr: 输入数组
  • obj: 可以是切片,即整数或整数数组,指示要从输入数组中删除的子数组。
  • axis: 要沿其删除给定子数组的轴。如果未给出,则输入数组 (arr) 将被展平。

示例 1

以下是 NumPy delete() 函数的基本示例,它删除索引为 5 的元素:

import numpy as np 

# Creating an array with shape (3, 4)
a = np.arange(12).reshape(3, 4)

print('First array:') 
print(a)
print('\n')

# Delete the element at index 5 from the flattened array
print('Array flattened before delete operation as axis not used:') 
print(np.delete(a, 5)) 

输出

First array:
[[ 0  1  2  3]
 [ 4  5  6  7]
 [ 8  9 10 11]]


Array flattened before delete operation as axis not used:
[ 0  1  2  3  4  6  7  8  9 10 11]

示例 2

在此示例中,我们使用 delete() 函数从二维数组中删除特定列:

import numpy as np

# Create a 3x4 array
a = np.arange(12).reshape(3, 4)

print('Original array:')
print(a)
print('\n')

# Delete the second column (index 1)
result = np.delete(a, 1, axis=1)
print('Array after deleting column 2:')
print(result)

输出

Original array:
[[ 0  1  2  3]
 [ 4  5  6  7]
 [ 8  9 10 11]]


Array after deleting column 2:
[[ 0  2  3]
 [ 4  6  7]
 [ 8 10 11]]

示例 3

我们可以使用切片从数组中删除多个元素。在下面的示例中,我们将切片模式作为参数传递给 delete() 函数以及输入数组:

import numpy as np

# Create a 1D array
a = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10])

print('Original array:')
print(a)
print('\n')

# Delete every second element
result = np.delete(a, np.s_[::2])
print('Array after deleting every second element:')
print(result)

输出

Original array:
[ 1  2  3  4  5  6  7  8  9 10]


Array after deleting every second element:
[ 2  4  6  8 10]
numpy_array_manipulation.htm
广告