Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add or remove a specific element from a numpy 2d array?

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(...)

like image 508
DragonKnight Avatar asked Feb 22 '19 08:02

DragonKnight


2 Answers

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)
like image 121
user2314737 Avatar answered Oct 11 '22 07:10

user2314737


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)
like image 25
K.Maj Avatar answered Oct 11 '22 05:10

K.Maj