Numpy ndarray-如何根据多列的值选择行

我有一个对象的2D速度值的x和y分量的ndarray,例如:

(Pdb) p highspeedentries
array([[  0.,52.57],[-40.58,70.89],[-57.32,76.47],[-57.92,65.1 ],[-52.47,96.68],[-45.58,77.12],[-37.83,69.52]])

(Pdb) p type(highspeedentries)
<class 'numpy.ndarray'>

我必须检查是否有任何行的第一和第二个成分的值大于55。我还需要对任何负速度分量取绝对值,但是首先我尝试了以下方法,所有这些都给出了错误。

(Pdb) p highspeedentries[highspeedentries[:,1] > 55 and highspeedentries[0,:] > 55]
*** ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()

(Pdb) p highspeedentries[highspeedentries[:,1] > 55 & highspeedentries[0,:] > 55]
*** TypeError: ufunc 'bitwise_and' not supported for the input types,and the inputs could not be 
safely coerced to any supported types according to the casting rule ''safe''

(Pdb) p highspeedentries[np.logical_and(highspeedentries[:,1] > 55,highspeedentries[0,:] > 55)]
*** ValueError: operands could not be broadcast together with shapes (7,) (2,)
sunlei890325sunlei 回答:Numpy ndarray-如何根据多列的值选择行

一种愚蠢的解决方法是只遍历整个数组以寻找状态:

for i in highspeedentries:
    if (abs(i[0]) > 55 and abs(i[1]) > 55):
        print('True')
        break
else:
    print('False')

或者,您在第三次尝试时处于正确的轨道:

logical_and(abs(highspeedentries[:,0]) > 55,abs(highspeedentries[:,1]) > 55).any()

索引的顺序不正确,如果在末尾添加.any(),则会得到单个值(如果至少一个元素为True,则为True,否则为False),而不是布尔数组。要应用绝对值,只需在与55比较之前将abs()应用于数组即可。

本文链接:https://www.f2er.com/3106077.html

大家都在问