Home > front end >  How to delete a specific element from a numpy nd array?
How to delete a specific element from a numpy nd array?

Time:12-20

I am working on nd-arrays whose dimensions can vary. I want to delete specific elements from the array given its index. like

x = [[1,2,3],[4,5,6]]
index = (0,0)

I am expecting to get the result as

modx = [[2,3],[4,5,6]]

I have tried numpy.delete() but this flattens the array.

CodePudding user response:

It's not considered a good practice to remove elements from numpy.array. As @Michael Szczesny pointed out, your desired solution is not a valid numpy.array.

Even if you remove elements in a way that is valid, the improvement in speed and memory usage of numpy.array does not justify the extra overhead to resize the array, especially if you need to remove elements often.

Instead, try to set the value to something considered invalid in your use case. For example, empty cells in a 9x9 sudoku grid can be represented by seting them to 0 or -1. It's much faster and more efficient.

CodePudding user response:

x = [[1,2,3],[4,5,6]]
index = (0,0)
x[index[0]].pop(index[1])
x  # this will return [[2,3],[4,5,6]]

Does this work ?

  • Related