使用'in'语句检查Pandas Series中是否存在一个值

3

我试图检查pandas系列中是否存在某个值,然而,我发现了一个有趣的事实:

s1 = pd.Series(['one', 'one1', '1', ''])
'one' in s1
False

'one' in set(s1)
True

为什么在Series对象上不能使用"in"操作?谢谢!

为什么Series需要实现in?它更多或少是np.ndarray的包装器,而np.ndarray已经实现了in,所以只需使用Series对象的values属性即可。 - NotAName
使用s.values来检查字符串。 - Saatvik Ramani
@pavel 谢谢。我只是纯粹好奇,因为我认为它会出于某种原因被实现。 - Kaihua Hou
1个回答

4

in 用于检查 index 是否在该系列中。

In[29]: s1.__contains__
Out[29]: 
<bound method NDFrame.__contains__ of 
0     one
1    one1
2       1
3        
dtype: object>

In[30]: 'one' in s1
Out[30]: False

In[31]: 0 in s1
Out[31]: True

In[32]: 1 in s1
Out[32]: True

In[33]: 2 in s1
Out[33]: True

In[34]: 3 in s1
Out[34]: True

In[35]: 4 in s1
Out[35]: False

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接