简体   繁体   中英

Removing ndarray from list in python

Very strange issue, giving you details for you to reproduce.

I have an ndarray x = [[ 58.0376135 ], [4739.44845915]] which is defined as ndarray size (2,1)

I also have this list

lst = [array([[11120.19965669],[ 1036.7331153 ]]), 
       array([[  58.0376135 ],[4739.44845915]]), 
       array([[ 766.38433838],[5524.3418457 ]])]

list of (2,1) ndarrays. As you can see, x == lst[1] .

However, when I write lst.remove(x) or x in lst I get value error that the truth value of an array with more than one element is ambiguous. Strangely, on other examples it does work.

How can I make it work here too?

This is a way to do it:

[arr for arr in lst if not np.all(x==arr)]

Since x is multidimensional you need to use np.all() instead of element-wise comparisons like x in arr

For a NumPy array arr , the expression arr in seq returns the element-wise in seq operation, ie, an array of booleans.

If the resulting array has only one element, then the expression is evaluated as True or False depending on the boolean value of that element. However, whenever you try to evaluate an array with more than one element in boolean context you get a ValueError , as in this case the truth value is ambiguous. You can remove ambiguity through any or all . Run this code to convince yourself:

In [1282]: x = np.array([0])

In [1283]: y = np.array([0, 1])

In [1284]: bool(x)
Out[1284]: False

In [1285]: bool(y)
Traceback (most recent call last):

  File "<ipython-input-1285-c0cc820b77c4>", line 1, in <module>
    bool(y)

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


In [1286]: any(y)
Out[1286]: True

In [1287]: all(y)
Out[1287]: False

If you want to check whether an array is contained in a list you could use NumPy's array_equal like this:

In [1295]: def array_in_list(arr, alist):
      ...:     for item in alist:
      ...:         if np.array_equal(arr, item):
      ...:             return True
      ...:     return False

In [1296]: array_in_list(x, lst)
Out[1296]: True

In [1297]: array_in_list(2*x, lst)
Out[1297]: False

It may be convenient to replace array_equal by allclose in order to avoid the issues associated to floating point comparison.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM