0

Is there a way to remove just a single element in a 2d numpy array?

For example, let's say I have: x = np.array([[1, 2], [3, 4]])

and I want the new version of x to just store np.array([[1], [3, 4]]).

Is this doable?

jj172
  • 751
  • 2
  • 9
  • 35
  • AFAIK you need to make a new array. – Divakar Jan 21 '17 at 10:23
  • 1
    Actually, have you tried entering `np.array([[1], [3, 4]])` to see what you get? I'm pretty sure it's not possible. Flatten it and then delete the unwanted element using the method described in the linked duplicate. – TigerhawkT3 Jan 21 '17 at 10:29
  • That's the wrong duplicate. This isn't a 1d array. `np.delete` does not work. Actually nothing works like this. – hpaulj Jan 21 '17 at 13:19
  • Show us how you would do this task on `x1=x.tolist()`. – hpaulj Jan 21 '17 at 13:40
  • wrong 1d array delete: http://stackoverflow.com/questions/10996140/how-to-remove-specific-elements-in-a-numpy-array; it may help asnwer the question, but it isn't a duplicate. – hpaulj Jan 21 '17 at 17:03

1 Answers1

0

As a list operation this is straight forward:

In [328]: x = np.array([[1, 2], [3, 4]])

Just use the list del to remove the desired element:

In [337]: xl=x.tolist()
In [338]: idx=(0,1)
In [339]: del xl[idx[0]][idx[1]]
In [340]: xl
Out[340]: [[1], [3, 4]]

It can be turned back into an array - but it will be jagged, and hence an array of lists:

In [341]: np.array(xl)
Out[341]: array([[1], [3, 4]], dtype=object)

You could also use np.delete to remove this element from a flattened version of the array:

In [343]: np.ravel_multi_index(idx,x.shape)
Out[343]: 1
In [344]: np.delete(x,np.ravel_multi_index(idx,x.shape))
Out[344]: array([1, 3, 4])

You can't go back to the 2d array. It could be split into row arrays:

In [345]: np.split(_,[1])
Out[345]: [array([1]), array([3, 4])]

Calculating that split index will be a bit more tedious in the general case.

hpaulj
  • 221,503
  • 14
  • 230
  • 353