How to delete a column in a numpy array?

Imagine we have a 5x4 matrix. We need to remove only the first dimension. How to do it with numpy ?

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

I tried:

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)

He looks a little awkward. Am I doing it right? If so, is there a cleaner way to remove a dimension without changing the shape?

+4
source share
3 answers

If you want to remove a column from a 2D Numpy array, you can specify columns like this

save all rows and get rid of column 0 (or start from column 1 to the end)

a[:,1:]

otherwise you can specify the columns you want to keep (and, if you want, change the order) This saves all rows and uses only columns 0,2,3

a[:,[0,2,3]]

-, , - :

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

@hpaulj numpy.delete()

"a" (0 2) = 1.

np.delete(a,[0,2],1)

'a', numpy.

+7

delete - , . 1- (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]])

, :

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])]
+2

A second change is not required.

matrix=np.delete(matrix,0,1)
+1
source

Source: https://habr.com/ru/post/1618028/


All Articles