Combining logic statements AND in numpy array

前端 未结 3 1673
情歌与酒
情歌与酒 2020-12-11 05:15

What would be the way to select elements when two conditions are True in a matrix? In R, it is basically possible to combine vectors of booleans.

So wha

3条回答
  •  南笙
    南笙 (楼主)
    2020-12-11 06:07

    There's a function for that:

    In [8]: np.logical_and(A < 3, A > 1)
    Out[8]: array([ True,  True,  True,  True,  True], dtype=bool)
    

    Since you can't override the and operator in Python it always tries to cast its arguments to bool. That's why the code you have gives an error.

    Numpy has defined the __and__ function for arrays which overrides the & operator. That's what the other answer is using.

提交回复
热议问题