Skip to main content
 首页 » 编程设计

python之检查两个包含系列的对象是否相等

2025年05月04日14shanyou

我正在尝试比较两个 Cashflow 对象,它们只包含一个 Series 作为单元测试的一部分。

在单元测试中,我有以下内容,其中 cashflowobj_1 和 cashflowobj_2 是包含 Series 的 Cashflow 对象:

self.assert_(cashflowobj_1==cashflowobj_2) 

这两个 Series 看起来完全一样,如下所示,但测试返回 Series are not equal,所以我想知道我正在使用的函数是否存在问题检查他们的平等。 cashflowobj_1.amounts 和 cashflowobj_2.amounts 是各自的 Series:

cashflowobj_1.amounts:

     1983-05-15      1 
     1983-11-15      1 
     1984-05-15      1 
     1984-11-15     101 

cashflowobj_2.amounts:

     1983-05-15      1 
     1983-11-15      1 
     1984-05-15      1 
     1984-11-15     101 

用于检查Cashflow对象是否相等的函数,在Cashflow类中:

def __eq__(self, other): 
    ''' 
    Series being equal 
    ''' 
    if ((len(self.amounts) == len(other.amounts))) and ((all(i in self.amounts for i in other.amounts))): 
        print('Series are equal') 
        return(1) 
    else: 
        print('Series are not equal') 
        return(0) 

编辑:解决@matt 的问题:索引都是 datetime.date() 对象。值是 float64。

请您参考如下方法:

你不是只想检查系列是否相等吗?假设您正在谈论 Pandas.Series。

使用 Series.equals()功能。

def __eq__(self, other): 
    ''' 
    Series being equal 
    ''' 
    if self.amounts.equals(other.amounts) 
        print('Series are equal') 
        return(1) 
    else: 
        print('Series are not equal') 
        return(0)