Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you 'remove' a numpy array from a list of numpy arrays?

Tags:

python

numpy

If I have a list of numpy arrays, then using remove method returns a value error.

For example:

import numpy as np

l = [np.array([1,1,1]),np.array([2,2,2]),np.array([3,3,3])]

l.remove(np.array([2,2,2]))

Would give me

ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()

I can't seem to get the all() to work, is it just not possible?

like image 950
matt_s Avatar asked Jul 01 '10 11:07

matt_s


People also ask

How do I completely remove NumPy array?

Using the NumPy function np. delete() , you can delete any row and column from the NumPy array ndarray . Specify the axis (dimension) and position (row number, column number, etc.). It is also possible to select multiple rows and columns using a slice or a list.

How do you remove an element from an array from another array in Python?

You can use the pop() method to remove an element from the array.


2 Answers

The problem here is that when two numpy arrays are compared with ==, as in the remove() and index() methods, a numpy array of boolean values (the element by element comparisons) is returned which is interpretted as being ambiguous. A good way to compare two numpy arrays for equality is to use numpy's array_equal() function.

Since the remove() method of lists doesn't have a key argument (like sort() does), I think that you need to make your own function to do this. Here's one that I made:

def removearray(L,arr):
    ind = 0
    size = len(L)
    while ind != size and not np.array_equal(L[ind],arr):
        ind += 1
    if ind != size:
        L.pop(ind)
    else:
        raise ValueError('array not found in list.')

If you need it to be faster then you could Cython-ize it.

like image 110
Justin Peel Avatar answered Sep 21 '22 04:09

Justin Peel


Here you go:

list.pop(1)

Update:

list.pop(list.index(element))

I don't think you can get around traversing the list to find the position of the element. Don't worry about it. Python will, by default use a good searching algorithm to find it at least cost for you.

like image 28
lprsd Avatar answered Sep 24 '22 04:09

lprsd