我该如何删除NumPy数组的多行?例如,我想删除x
的前五行。我正在尝试以下代码:
import numpy as np
x = np.random.rand(10, 5)
np.delete(x, (0:5), axis=0)
但它并不起作用:
np.delete(x, (0:5), axis=0)
^
SyntaxError: invalid syntax
有几种方法可以从NumPy数组中删除行。
最简单的方法是像标准Python列表一样使用 基本索引 :
>>> import numpy as np
>>> x = np.arange(35).reshape(7, 5)
>>> x
array([[ 0, 1, 2, 3, 4],
[ 5, 6, 7, 8, 9],
[10, 11, 12, 13, 14],
[15, 16, 17, 18, 19],
[20, 21, 22, 23, 24],
[25, 26, 27, 28, 29],
[30, 31, 32, 33, 34]])
>>> result = x[5:]
>>> result
array([[25, 26, 27, 28, 29],
[30, 31, 32, 33, 34]])
您不仅可以选择行,还可以选择列:
>>> x[:2, 1:4]
array([[1, 2, 3],
[6, 7, 8]])
另一种方法是使用“fancy indexing”(使用数组来索引数组):>>> x[[0, 2, 6]]
array([[ 0, 1, 2, 3, 4],
[10, 11, 12, 13, 14],
[30, 31, 32, 33, 34]])
你可以使用np.take
来实现相同的功能。>>> np.take(x, [0, 2, 6], axis=0)
array([[ 0, 1, 2, 3, 4],
[10, 11, 12, 13, 14],
[30, 31, 32, 33, 34]])
另一个选择是使用np.delete
,就像问题中一样。为了选择要删除的行/列,它可以接受slice
对象、int
或整数数组: >>> np.delete(x, slice(0, 5), axis=0)
array([[25, 26, 27, 28, 29],
[30, 31, 32, 33, 34]])
>>> np.delete(x, [0, 2, 3], axis=0)
array([[ 5, 6, 7, 8, 9],
[20, 21, 22, 23, 24],
[25, 26, 27, 28, 29],
[30, 31, 32, 33, 34]])
但是在我使用NumPy的所有时间里,我从来没有需要过 np.delete
,因为在这种情况下,使用 布尔索引 更方便。
例如,如果我想删除 / 选择那些以大于12的值开头的行,我会这样做:
>>> mask_array = x[:, 0] < 12 # comparing values of the first column
>>> mask_array
array([ True, True, True, False, False, False, False])
>>> x[mask_array]
array([[ 0, 1, 2, 3, 4],
[ 5, 6, 7, 8, 9],
[10, 11, 12, 13, 14]])
>>> x[~mask_array] # ~ is an element-wise inversion
array([[15, 16, 17, 18, 19],
[20, 21, 22, 23, 24],
[25, 26, 27, 28, 29],
[30, 31, 32, 33, 34]])
更多信息请参考有关索引的文档:https://docs.scipy.org/doc/numpy/reference/arrays.indexing.html。np.delete(x, (1,2,5), axis = 0)
np.delete(x, np.s_[0:5], axis = 0)
通过这种方法,您可以从数组中删除0到4行。
np.s_[0:5] --->> slice(0, 5, None) 两者是相同的。
np.delete(array_name,[rownumber1,rownumber2,..,rownumber n],axis=0)
示例:删除数组中的前三行:
np.delete(array_name,[0,1,2],axis=0)