【问题标题】:Comparing two dataframes pandas比较两个数据框熊猫
【发布时间】:2020-06-23 18:58:06
【问题描述】:

我有两个都包含数字的数据框。它们都具有相同的大小 10x350(十列和 350 行)我想比较它们并“做一些逻辑”

这里有一些摘录作为说明:

Dataframe 1:               Dataframe 2:
A      B     C             A      B     C
47.7   20.2  12.1          90.7   73.8  216.7
47.2   20    11.9          114.9  68    155.6
46.4   19.6  11.7          110.8  67.8  160.3

我想比较数据帧,如果数据帧 2 的值更高,则存储差异。
(在此示例中,数据帧 2 中的所有值都较高) 最后,所有与列的差异都应加起来

在这种情况下,差异的总和是:

Sum_A = 175.1
Sum_B = 149.8
Sum_C = 496.9

我认为使用:

for index, row in df1.iterrows():

也许是可能的。但是我无法比较两个数据框的工作

【问题讨论】:

  • 到目前为止你有什么尝试?
  • 我尝试遍历数据框。但我只让它一次迭代一个数据帧,而不是两个
  • "如果来自 Dataframe 2 的值更高,则存储差异。" --> 存储它是不是更高?
  • 然后将 Sum 减去该差值。最小值应为零

标签: python pandas dataframe compare difference


【解决方案1】:

你可以这样做:

df2.sub(df1).clip(lower=0).sum()

输出:

A    175.1
B    149.8
C    496.9
dtype: float64

【讨论】:

    【解决方案2】:
    def VerifyTable(context,actual_table, expected_table):
                n = []
                for actual_tablecolumns in actual_table.columns:
                    n.append(actual_tablecolumns)
                print (n)
                m = []
                for expected_tablecolumns in expected_table.columns:
                    m.append(expected_tablecolumns)
                print (m)
                if n == m:
                    for actual_tablevalues in actual_table.values:
                        nn.append(actual_tablevalues)
                    print (nn)
                    mm = []
                    for expected_tablevalues in expected_table.values:
                        mm.append(expected_tablevalues)
                    if nn == mm:
                        return True
    
                return False
    

    另一个代码

    def VerifyTable(context, actual_table, expected_table):
        #print("row count in actual table: " + str(len(actual_table.values)))
        currentRowIndex = -1
        currentColIndex = -1
        for row in actual_table.values:
            currentRowIndex = currentRowIndex + 1
            currentColIndex = -1 #reset column index
            for cell_by_column in row:
                currentColIndex = currentColIndex + 1
                assert cell_by_column == expected_table.values[currentRowIndex][currentColIndex], "Mismatch of corresponding cells comparing actual and expected: " + cell_by_column + " != " + expected_table.values[currentRowIndex][currentColIndex]
        #TODO: Write code to compare/verify column headers as well!
       
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-11-23
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多