How do I remove an array from an array in numpy?

Viewed 78

If I have

a = [[1, 1], [1, 2]]
b = [[1, 1], [1, 2], [1, 3]]

Where a and b are numpy arrays, how can I get this?

c = b - a = [[1, 3]]

Because np.delete does it by index not value. I have tried to create a new array like this

for arr in b:
    if arr not in a:
        new.append(arr)

But it doesn't work, what am I doing wrong?

2 Answers

A few observations you should know:

  1. numpy has nothing to do with what you showed.
  2. What you showed uses built-in Python lists
  3. To remove an item from a Python list, use remove. This is a o(n) operation.
  4. Working code:
a = [1, 1]
b = [[1, 1], [1, 2]]

print(b)
b.remove(a)
print(b)

out:

[[1, 1], [1, 2]]
[[1, 2]]

Python provides a very powerful list feature "List Comprenhensions" that produce an effective and versatile way to conduct list manipulations in a very adaptable manner.

Considering the input lists you have provided, the output can be dervied within an optimal complexity :

  a = [1, 1]
  b = [[1, 1], [1, 2]]
  c = [x for x in b if x != a]
  print(c)

Printing 'c' will provide you :

[[1, 2]]

Note: Using built - in list method of remove() also assists in the same, but I just wanted to emphasize on the value of List Comprehensions in a dynamic language like Python.

Related