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

后端 未结 4 1990
北海茫月
北海茫月 2021-01-11 13:43

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         


        
4条回答
  •  一生所求
    2021-01-11 14:20

    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.

提交回复
热议问题