I have an ND array, and I want to delete a specific row by value, How to do so? Currently, the output is an empty list.
import numpy as np
def delete_item(array, item):
new_a = np.delete(array, np.where(array == item), axis=0)
return new_a
a = np.array([[1, 1, 1], [85, 32, 531], [78, 91, 79]])
new_array = delete_item(a, [1, 1, 1]) # -> it returns empty list []
"""
The output is:
[]
What i want is:
[[85, 32, 531],
[78, 91, 79]]
"""
print(new_array)
CodePudding user response:
Here is one possibility:
def delete_item(array, item):
new_a = array.copy()
return new_a[(array != item).any(1)]
# or
# return np.delete(array, np.where((array == item).all(1))[0], axis=0)
a = np.array([[1, 1, 1], [85, 32, 531], [78, 91, 79]])
new_array = delete_item(a, [1, 1, 1])
output:
array([[ 85, 32, 531],
[ 78, 91, 79]])
CodePudding user response:
The issue is in your comparison operator within where
. This works:
def delete_item(array, item):
new_a = np.delete(array, np.all(array == item, axis=1), axis=0)
return new_a
Originally, array == item
gives:
[[ True True True]
[False False False]
[False False False]]
which provides an element by element comparison broadcasting [1, 1, 1]
appropriately. Using np.all(array == item, axis=1))
gives:
[ True False False]
which is what you want. In fact, you do not need the np.where
.