Numpy array : NOT select specific rows or columns

Viewed 1851

I have a simple numpy array. I want to select all rows but 1st and 6th I tried:

temp = np.array([1,2,3,4,5,6,7,8,9])
t = temp[~[0,5]]

I get the following error:

 TypeError: bad operand type for unary ~: 'list'

What is the correct way to do this?

3 Answers

You can use numpy.delete to delete elements at a specific index position:

t = np.delete(temp, [0, 5])

Or you can create an boolean array, than it is possible to negate the indices:

bool_idx = np.zeros(len(temp), dtype=bool)
bool_idx[[0, 5]] = True
t = temp[~bool_idx]

You cant create the indices that way. Instead you could create a range of numbers from 0 to temp.size and delete the unwanted indices:

In [19]: ind = np.delete(np.arange(temp.size), [0, 5])

In [21]: temp[ind]
Out[21]: array([2, 3, 4, 5, 7, 8, 9])

Or just create it like following:

In [16]: ind = np.concatenate((np.arange(1, 5), np.arange(6, temp.size)))

In [17]: temp[ind]
Out[17]: array([2, 3, 4, 5, 7, 8, 9])

You can use the np.r_ numpy object which concatenates the array into by breaking them using the indices giving the resultant output.

np.r_[temp[1:5], temp[6:]]

The code above concatenates the two arrays which are sliced from the original array and hence the resultant array without the indices specified.

Related