Find and delete column from numpy array

Viewed 81

I'm trying to remove specific columns from an array:

data = array([[ 6,  3,  3],
              [ 7,  4, -1]])

target = array([[3]
                [-1]])

I want to find the index of the column within data which is identical to target, so that I can call:

np.delete(data, index, axis=1)

It looks like some combination of all and where might be the answer, but I just can't get it to work out.

1 Answers

The mask (data == target).all(axis=0) will check for equality along the columns. You don't need to do anything with where or delete. Just use the mask as-is:

mask = (data == target).all(axis=0)
data = data[:, ~mask]

In fact, it may be faster to compute the mask of non-identical elements, since those are the ones you want to keep.

mask = (data != target).any(axis=0)
data = data[:, mask]
Related