如何从numpy数组列表中“删除"一个numpy数组?
如果我有一个numpy数组列表,则使用remove方法将返回值错误.
If I have a list of numpy arrays, then using remove method returns a value error.
例如:
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]))
请给我
ValueError:具有多个元素的数组的真值不明确.使用a.any()或a.all()
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
我似乎无法使all()工作,这是不可能的吗?
I can't seem to get the all() to work, is it just not possible?
这里的问题是,当两个numpy数组与==进行比较时,如remove()和index()方法中那样,一个numpy布尔值数组(逐个元素比较)将返回,这被解释为模棱两可.比较两个numpy数组是否相等的一种好方法是使用numpy的array_equal()函数.
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.
由于列表的remove()方法没有键参数(就像sort()一样),因此我认为您需要创建自己的函数才能执行此操作.这是我做的:
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.')
如果您需要更快的速度,则可以对其进行Cython化.
If you need it to be faster then you could Cython-ize it.