如何删除numpy数组中的列?

min*_*als 10 python arrays numpy

想象一下,我们有一个5x4矩阵.我们只需删除第一个维度.我们怎么能用numpy做到这一点?

array([[  0.,   1.,   2.,   3.],
       [  4.,   5.,   6.,   7.],
       [  8.,   9.,  10.,  11.],
       [ 12.,  13.,  14.,  15.],
       [ 16.,  17.,  18.,  19.]], dtype=float32)
Run Code Online (Sandbox Code Playgroud)

我试过了:

arr = np.arange(20, dtype=np.float32)
matrix = arr.reshape(5, 4)
new_arr = numpy.delete(matrix, matrix[:,0])
trimmed_matrix = new_arr.reshape(5, 3)
Run Code Online (Sandbox Code Playgroud)

它看起来有点笨重.我做得对吗?如果是,是否有更简洁的方法来移除尺寸而不重塑?

Bac*_*ics 28

如果要从2D Numpy数组中删除列,可以指定这样的列

保留所有行并摆脱第0列(或从第1列开始到结尾)

a[:,1:]
Run Code Online (Sandbox Code Playgroud)

另一种方法,你可以指定你想要保留的列(并根据需要更改顺序)这将保留所有行,只使用列0,2,3

a[:,[0,2,3]]
Run Code Online (Sandbox Code Playgroud)

有关这方面的文档可以在这里找到

如果你想要一些特别删除列的东西,你可以这样做:

idxs = list.range(4)
idxs.pop(2) #this removes elements from the list
a[:, idxs]
Run Code Online (Sandbox Code Playgroud)

和@hpaulj提出了numpy.delete()

这将是如何返回"a"的视图,其中沿着轴= 1移除了2列(0和2).

np.delete(a,[0,2],1)
Run Code Online (Sandbox Code Playgroud)

这实际上并没有从'a'中删除项目,它的返回值是一个新的numpy数组.


hpa*_*ulj 5

正确的使用方法delete是指定索引和维数,例如。删除第一(0)列(维度1):

In [215]: np.delete(np.arange(20).reshape(5,4),0,1)
Out[215]: 
array([[ 1,  2,  3],
       [ 5,  6,  7],
       [ 9, 10, 11],
       [13, 14, 15],
       [17, 18, 19]])
Run Code Online (Sandbox Code Playgroud)

其他有效的表达式:

np.arange(20).reshape(5,4)[:,1:]
np.arange(20).reshape(5,4)[:,[1,2,3]]
np.arange(20).reshape(5,4)[:,np.array([False,True,True,True])]
Run Code Online (Sandbox Code Playgroud)