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?
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?
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.