How to delete columns in numpy.array

Boris Gorelik picture Boris Gorelik · Oct 29, 2009 · Viewed 189.1k times · Source

I would like to delete selected columns in a numpy.array . This is what I do:

n [397]: a = array([[ NaN,   2.,   3., NaN],
   .....:        [  1.,   2.,   3., 9]])

In [398]: print a
[[ NaN   2.   3.  NaN]
 [  1.   2.   3.   9.]]

In [399]: z = any(isnan(a), axis=0)

In [400]: print z
[ True False False  True]

In [401]: delete(a, z, axis = 1)
Out[401]:
 array([[  3.,  NaN],
       [  3.,   9.]])

In this example my goal is to delete all the columns that contain NaN's. I expect the last command to result in:

array([[2., 3.],
       [2., 3.]])

How can I do that?

Answer

Steve Tjoa picture Steve Tjoa · Feb 17, 2011

Given its name, I think the standard way should be delete:

import numpy as np

A = np.delete(A, 1, 0)  # delete second row of A
B = np.delete(B, 2, 0)  # delete third row of B
C = np.delete(C, 1, 1)  # delete second column of C

According to numpy's documentation page, the parameters for numpy.delete are as follow:

numpy.delete(arr, obj, axis=None)

  • arr refers to the input array,
  • obj refers to which sub-arrays (e.g. column/row no. or slice of the array) and
  • axis refers to either column wise (axis = 1) or row-wise (axis = 0) delete operation.