2

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)

2 Answers 2

2

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]])
Sign up to request clarification or add additional context in comments.

Comments

1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.