Reputation: 155
I want delete the array from list of arrays in that way
i = np.array([1,2])
facets = [np.array([1,2]),np.array([3,4])]
I want remove an element
facets.remove(np.array(i[0],i[1]))
but obtain an error:
ValueError Traceback (most recent call last)
<ipython-input-131-c0d040653e23> in <module>()
----> 1 facets.remove([i[0],i[2]])
ValueError: The truth value of an array with more than one element is ambiguous.
Use a.any() or a.all()
Is there a way to solve that problem?
Upvotes: 3
Views: 20169
Reputation: 9010
Consider the following example:
ls = [1, 2, 3, 1]
ls.remove(1)
This code does something like:
ls
.1
.In step 2, your code is trying to compare two numpy arrays like array1 == array2
. The problem is that numpy returns an array of truth values for this comparison.
>>> np.array([1,2]) == np.array([1,3])
array([ True, False], dtype=bool)
So, you're going to have to implement your own remove-like method.
def remove_from_array(base_array, test_array):
for index in range(len(base_array)):
if np.array_equal(base_array[index], test_array):
base_array.pop(index)
break
raise ValueError('remove_from_array(array, x): x not in array')
Usage:
i = np.array([1,2])
facets = [np.array([1,2]),np.array([3,4])]
remove_from_array(facets, i)
print facets # [array([3, 4])]
Upvotes: 4
Reputation: 2210
Try below :
facets.remove(np.array(i[0],i[1]))
This worked for me as follows :
>>> i = list([1,2])
>>> facets = [list([1,2]),list([3,4])]
>>> facets.remove(list([i[0],i[1]]))
>>> facets
[[3, 4]]
Upvotes: 0
Reputation: 7796
The easiest way is to use all()
to compare the list element-by-element to the element you want to remove and return all that do not match. Note that this removes all elements of your list that match the array you want to remove.
[ x for x in facets if not (x==i).all()]
Upvotes: 3