Let's say that I have an array something like:
foo = np.random.rand(2, 5)
and I've been given a slice like [:, [2, 4]]. What I'd like to do is to efficiently be able to delete the slice out of the array, so basically leaving me with:
foo[:, [0, 1, 3]]
Here foo could be an arbitrary rank tensor with the slice in each dimension being either a : or a list of non-repeating positive indices. Is there an efficient way of implementing this without using np.delete and a complicated (slow) loop?
Given an input list of column indices you wish to remove, you can remove these elements from a list of all indices.
Simpler still, you can utilize set.difference to remove the necessary columns:
foo[:, sorted(set(range(foo.shape[1])) - set([2, 4]))]
To select specific rows or columns, you should not need to use numpy.delete. As you found, this is inefficient with NumPy.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With