Python equivalent of the R operator "%in%" Python equivalent of the R operator "%in%" r r

Python equivalent of the R operator "%in%"


Pandas comparison with R docs are here.

s <- 0:4s %in% c(2,4)

The isin() method is similar to R %in% operator:

In [13]: s = pd.Series(np.arange(5),dtype=np.float32)In [14]: s.isin([2, 4])Out[14]: 0    False1    False2     True3    False4     Truedtype: bool


FWIW: without having to call pandas, here's the answer using a for loop and list compression in pure python

x = [2, 3, 5] y = [1, 2, 3]# for loopfor i in x: [].append(i in y)Out: [True, True, False]# list comprehension[i in y for i in x]Out: [True, True, False]


If you want to use only numpy without panads (like a use case I had) then you can:

import numpy as npx = np.array([1, 2, 3, 10])y = np.array([10, 11, 2])np.isin(y, x)

This is equivalent to:

c(10, 11, 2) %in% c(1, 2, 3, 10)

Note that the last line will work only for numpy >= 1.13.0, for older versions you'll need to use np.in1d.