pandas Python 等效于 R 运算符“%in%”

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/25206376/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-13 22:21:12  来源:igfitidea点击:

Python equivalent of the R operator "%in%"

pythonrpandas

提问by wolfsatthedoor

What is the python equivalent of this in operator? I am trying to filter down a pandas database by having rows only remain if a column in the row has a value found in my list.

运算符中 this 的 Python 等价物是什么?我试图通过仅当行中的列在我的列表中找到值时才保留行来过滤 Pandas 数据库。

I tried using any() and am having immense difficulty with this.

我尝试使用 any() 并且在这方面遇到了巨大的困难。

回答by Jeff

Pandas comparison with R docs are here.

Pandas 与 R 文档的比较在这里

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

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

isin() 方法类似于 R %in% 运算符:

In [13]: s = pd.Series(np.arange(5),dtype=np.float32)

In [14]: s.isin([2, 4])
Out[14]: 
0    False
1    False
2     True
3    False
4     True
dtype: bool

回答by data_steve

FWIW: without having to call pandas, here's the answer using a for loopand list compressionin pure python

FWIW:无需调用Pandas,这是在纯 python 中使用 afor loop和的答案list compression

x = [2, 3, 5] 
y = [1, 2, 3]

# for loop
for i in x: [].append(i in y)

Out: [True, True, False]


# list comprehension
[i in y for i in x]

Out: [True, True, False]

回答by stok

As others indicate, inoperator of base Python works well.

正如其他人所指出的,in基本 Python 的运算符运行良好。

myList = ["a00", "b000", "c0"]

"a00" in myList
# True

"a" in myList
# False