Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Element-wise logical OR in Pandas

I would like the element-wise logical OR operator. I know "or" itself is not what I am looking for.

I am aware that AND corresponds to & and NOT, ~. But what about OR?

like image 631
Keith Avatar asked Jul 16 '14 08:07

Keith


People also ask

What is element-wise in pandas?

Element-wise means handling data element by element.

How do pandas use logical operators?

The operators are: | for or , & for and , and ~ for not . These must be grouped by using parentheses, since by default Python will evaluate an expression such as df. A > 2 & df. B < 3 as df.

What does element-wise operation mean?

An element-wise operation is an operation between two tensors that operates on corresponding elements within the respective tensors. An element-wise operation operates on corresponding elements between tensors. Two elements are said to be corresponding if the two elements occupy the same position within the tensor.

What are the 3 data structures in pandas?

Pandas DataFrame consists of three principal components, the data, rows, and columns.


1 Answers

The corresponding operator is |:

 df[(df < 3) | (df == 5)] 

would elementwise check if value is less than 3 or equal to 5.


If you need a function to do this, we have np.logical_or. For two conditions, you can use

df[np.logical_or(df<3, df==5)] 

Or, for multiple conditions use the logical_or.reduce,

df[np.logical_or.reduce([df<3, df==5])] 

Since the conditions are specified as individual arguments, parentheses grouping is not needed.

More information on logical operations with pandas can be found here.

like image 187
deinonychusaur Avatar answered Oct 27 '22 05:10

deinonychusaur