我有以下数组:
import numpy as np
a = [np.array([52.941, 57.962]),
np.array([52.918, 57.96 ]),
np.array([52.908, 57.958]),
np.array([52.898, 57.957]),
np.array([52.878, 57.953]),
np.array([52.868, 57.952]),
np.array([52.813, 57.941])]
现在我想测试数组 test = np.array([52.908, 57.958])
是否是上面提到的数组的一部分,如果它是数组的一部分,则删除它。
如何查看并删除它?
我尝试过:
if test in a:
print('okay')
和
a.remove(test)
...但它不起作用。
我收到以下错误:
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
这是什么意思?
最佳答案
使用数组列表会阻止您利用 NumPy 的矢量化功能。您可以转换为单个数组,这可以解决您的问题:
a = np.array(a)
if test in a:
print('match found!')
但此时您可以使用 bool 数组进行索引:
res = a[~(a == test).all(1)]
array([[ 52.941, 57.962],
[ 52.918, 57.96 ],
[ 52.898, 57.957],
[ 52.878, 57.953],
[ 52.868, 57.952],
[ 52.813, 57.941]])
如果您担心浮点近似,可以使用 np.allclose
与 np.apply_along_axis
:
def test_close(b):
return np.allclose(test, b)
res = a[~np.apply_along_axis(test_close, 1, a)]
关于python - 测试数组是否是数组数组的一部分并将其删除,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53205455/