2

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?

codeherk
  • 1,609
  • 15
  • 24
Anuj Gupta
  • 6,328
  • 7
  • 36
  • 55
  • Possible duplicate of [How to remove specific elements in a numpy array](https://stackoverflow.com/questions/10996140/how-to-remove-specific-elements-in-a-numpy-array) – zronn Jun 19 '19 at 09:16

3 Answers3

2

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]
scleronomic
  • 4,392
  • 1
  • 13
  • 43
1

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])
Mazdak
  • 105,000
  • 18
  • 159
  • 188
-1

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.

Saahil
  • 54
  • 4