Numpy ndarray如何基于多列的值选择行

2024-09-28 05:16:57 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个物体二维速度值的x和y分量的数组,例如:

(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,)

Tags: andthe方法withnotanyarray速度
1条回答
网友
1楼 · 发布于 2024-09-28 05:16:57

一种愚蠢的方法是在整个数组上循环查找您的状态:

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),而不是布尔数组。要应用绝对值,只需将abs()应用于数组,然后再与55进行比较

相关问题 更多 >

    热门问题