2016-12-31 68 views
7

考虑一系列s为什么大熊猫 '==' 不同于 '.EQ()'

s = pd.Series([(1, 2), (3, 4), (5, 6)]) 

这是预期

s == (3, 4) 

0 False 
1  True 
2 False 
dtype: bool 

这不是

s.eq((3, 4)) 
--------------------------------------------------------------------------- 
ValueError        Traceback (most recent call last) 

ValueError: Lengths must be equal 

我是在假设他们是相同的。他们有什么区别?


什么是documentation说?

相当于系列==其他,但与支持代替一个fill_value在其中的一个输入缺失数据。

这似乎意味着他们应该工作相同,因此混乱。

+0

@piRSquared:现在你已经在帖子中增加了一些研究成果的证据!起初你只是说过你已经假定了X事物并将它留在那个 –

回答

3

您遇到的情况实际上是一种特殊情况,它可以比较pandas.Seriesnumpy.ndarray与普通的python结构。源代码如下:

def flex_wrapper(self, other, level=None, fill_value=None, axis=0): 
    # validate axis 
    if axis is not None: 
     self._get_axis_number(axis) 
    if isinstance(other, ABCSeries): 
     return self._binop(other, op, level=level, fill_value=fill_value) 
    elif isinstance(other, (np.ndarray, list, tuple)): 
     if len(other) != len(self): 
      # --------------------------------------- 
      # you never reach the `==` path because you get into this. 
      # --------------------------------------- 
      raise ValueError('Lengths must be equal') 
     return self._binop(self._constructor(other, self.index), op, 
          level=level, fill_value=fill_value) 
    else: 
     if fill_value is not None: 
      self = self.fillna(fill_value) 

     return self._constructor(op(self, other), 
           self.index).__finalize__(self) 

你打的ValueError因为熊猫承担.eq,你想转换为而不是(如果你给它一个数组,列表或元组numpy.ndarraypandas.Series值实际上将其与tuple进行比较。例如,如果您有:

s = pd.Series([1,2,3]) 
s.eq([1,2,3]) 

你不希望它的每个元素比较[1,2,3]

问题是object阵列(与dtype=uint一样)经常滑过裂纹或被故意忽略。一个简单的if self.dtype != 'object'分支内的那个方法可以解决这个问题。但也许开发商有充分的理由让这个案例变得不同。我建议通过张贴在他们的bug tracker上来要求澄清。


你还没有问你如何使它正常工作,但completness我会包括一个可能性(根据源代码,它很可能你需要用它作为自己pandas.Series):

>>> s.eq(pd.Series([(1, 2)])) 
0  True 
1 False 
2 False 
dtype: bool 
0

==是一个元素明智的比较,产生一个真值的向量,而.eq是一个“那两个迭代是相等的”,对于它来说,长度相同是需求。 Ayhan指出了一个例外:当您使用.eq(scalar value)比较熊猫矢量类型时,标量值只是广播到相同大小的矢量进行比较。

+1

它实际上使用了一个标量进行广播:例如's.eq(3)'。 – ayhan