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

2024-09-30 01:32:56 发布

您现在位置:Python中文网/ 问答频道 /正文

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文件并打印它们的区别,我不太清楚前两行后面的逻辑,有人能解释一下吗,非常感谢。你知道吗


Tags: columns文件csv代码outputstack逻辑results
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

not equal to表达式!=只返回一个新的df,其中值不相等。你知道吗

enter image description here

stack用新索引重塑数据帧。更多信息here。你知道吗

enter image description here

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

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

下面一行从原始数据帧中过滤掉所有假值。你知道吗

enter image description here

注意索引2 B是如何丢失的,因为resultBooldf中的值是false。你知道吗

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

我们对df2也做了同样的工作,只是水平地连接结果。有关熊猫连接here的详细信息。你知道吗

enter image description here

在上图中,列“0”引用df1中的值,列“1”引用df2中的值。你知道吗

最后,我们将这些列重命名为“output\u 01”和“output\u 02”:

enter image description here

最终结果是一个新的df高亮显示两个数据帧中不同的值。你知道吗

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

resultdiff通过传入resultBool水平地执行pd.concat,这只会保存前面提到的resultBool的结果。你知道吗

之后,resultdiff设置列。你知道吗

有关更多信息,您应该查看所涉及的函数,以及在每行代码之后打印数据帧,以查看发生了什么。你知道吗

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

相关问题 更多 >

    热门问题