有人可以解释这段代码来识别两个数据帧之间的差异吗?

问题描述 投票:0回答:2
resultBool = (results_01 != results_02).stack() 
resultdiff = pd.concat([results_01.stack()[resultBool], results_02.stack()[resultBool]], axis=1)
resultdiff.columns=["output_01", "output_02"]

我在网上找到了这段代码,用于比较两个csv文件并打印出差异,我不太确定前两行背后的逻辑,有人可以解释很多谢谢。

python pandas dataframe stack concat
2个回答
2
投票

例如,下面考虑两个新创建的数据框:

import pandas as pd

# Creating the first dataframe
df1 = pd.DataFrame({"A":[1,5,7,8], 
                  "B":[5,8,4,3], 
                  "C":[10,4,9,3]}) 

# Creating the second dataframe 
df2 = pd.DataFrame({"A":[5,3,6,4], 
                  "B":[11,2,4,3], 
                  "C":[4,3,8,5]})

它们看起来像这样:

enter image description here

等于表达式!=的不等于]仅返回一个带有真/假的new df,其中值不等于

enter image description here

stack使用新索引重塑数据框。更多信息here

enter image description here

resultBool = (df1 != df2).stack() 

上面的行将结果df(如第二张图片所示)保存在变量中。

以下行从我们的原始数据框中过滤出所有错误值。

enter image description here

注意:由于2 B df中的值为false,因此缺少索引resultBool

这意味着此特定单元格的df1和df2中的值相等,因此!=运算符的结果为false。

我们对df2做同样的事情,只是简单地将结果水平连接。有关熊猫串联here的更多信息。

enter image description here

在上图中,列“ 0”是指df1中的值,列“ 1”是指df2中的值。

最后,我们将这些列重命名为'output_01'和'output_02':

enter image description here

最终结果是在两个数据框中都不同的新df高亮值。


0
投票

resultBoolDataFrame.stack()的结果,该结果将名为result_01result_02的2个csv文件的结果分解为TrueFalse值的单列,现在将列名堆叠为MultiIndex代表两者之间是否存在差异,True代表自results_01 != results_02以来的差异。

resultdiff通过传入pd.concat来水平执行resultBool,这只会保存上述resultBool的结果。

之后,resultdiff正在设置列。

有关更多信息,您应该查看所涉及的熊猫函数,并在每行代码之后打印数据框以查看发生了什么。

https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.stack.htmlhttps://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.concat.html

© www.soinside.com 2019 - 2024. All rights reserved.