Given the following numpy array:
arr = np.array([
[1,2,3],
[4,5,6],
[7,8,9]
])
delete and return:
arr = np.array([
[1,2,3],
[4,6],
[7,8,9]
])
I want to delete 5 from this array. or delete arr[1][2] only. When I am using del arr[i][j]
it throws the following err. ValueError: cannot delete array elements
and numpy documentation is not clear on this case for me.
Similarly how to add an element to some rows in the same array?
To be specific, When I am reading an image with opencv I am getting this err.
rgb_image = cv2.imread("image.png")
del
operation gives me the top error and I couldnt make it with np.delete(...)
A numpy array (ndarray
) is quote:
An ndarray is a (usually fixed-size) multidimensional container of items of the same type and size.
So you cannot have rows of different lengths if you want to use the ndarray
data structure (with all of its optimizations).
A possible workaround is to have an array of lists
>>> arr=np.array([
[1,2,3],
[4,5,6],
[7,8,9],
[]
])
(note the empty row to escape the ndarray datatype)
so you can delete an element from one of the lists
>>> arr
array([list([1, 2, 3]), list([4, 5, 6]), list([7, 8, 9]), list([])],
dtype=object)
>>> arr[1]=np.delete(arr[1], [1], axis=0)
>>> arr
array([list([1, 2, 3]), array([4, 6]), list([7, 8, 9]), list([])],
dtype=object)
I think the one way would be to cast np.array to list and repeat cast to np.array, like this:
arr = arr.tolist()
arr[1].pop(1)
arr = np.array(arr)
Edit: It seems to be right, numpy way:
np.delete(arr, [4, 4])
np.split(arr, [3, 5, 9])
Edit2: Doesn't seems to be less time consuming, but you could check this way:
arr = np.empty(3, dtype=np.object)
arr[:] = [1,2,3], [4,5,6], [7,8,9]
arr[1].remove(5)
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