当前位置: 首页 > 面试题库 >

比较两个DataFrame并并排输出它们的差异

聂和宜
2023-03-14
问题内容

我试图突出显示两个数据框之间到底发生了什么变化。

假设我有两个Python Pandas数据框:

"StudentRoster Jan-1":
id   Name   score                    isEnrolled           Comment
111  Jack   2.17                     True                 He was late to class
112  Nick   1.11                     False                Graduated
113  Zoe    4.12                     True

"StudentRoster Jan-2":
id   Name   score                    isEnrolled           Comment
111  Jack   2.17                     True                 He was late to class
112  Nick   1.21                     False                Graduated
113  Zoe    4.12                     False                On vacation

我的目标是输出一个HTML表:

  1. 标识已更改的行(可以是int,float,boolean,string)
  2. 输出具有相同,OLD和NEW值的行(理想情况下,将其输出到HTML表中),以便使用者可以清楚地看到两个数据框之间的变化:
    "StudentRoster Difference Jan-1 - Jan-2":
    

    id Name score isEnrolled Comment
    112 Nick was 1.11| now 1.21 False Graduated
    113 Zoe 4.12 was True | now False was “” | now “On vacation”

我想我可以逐行和逐列进行比较,但是有没有更简单的方法?


问题答案:

第一部分类似于君士坦丁,您可以获取哪些行为空的布尔值*:

In [21]: ne = (df1 != df2).any(1)

In [22]: ne
Out[22]:
0    False
1     True
2     True
dtype: bool

然后,我们可以查看哪些条目已更改:

In [23]: ne_stacked = (df1 != df2).stack()

In [24]: changed = ne_stacked[ne_stacked]

In [25]: changed.index.names = ['id', 'col']

In [26]: changed
Out[26]:
id  col
1   score         True
2   isEnrolled    True
    Comment       True
dtype: bool

在这里,第一个条目是索引,第二个条目是已更改的列。

In [27]: difference_locations = np.where(df1 != df2)

In [28]: changed_from = df1.values[difference_locations]

In [29]: changed_to = df2.values[difference_locations]

In [30]: pd.DataFrame({'from': changed_from, 'to': changed_to}, index=changed.index)
Out[30]:
               from           to
id col
1  score       1.11         1.21
2  isEnrolled  True        False
   Comment     None  On vacation

*注:这是非常重要的df1,并df2在这里分享相同的索引。为了克服这种歧义,您可以确保仅使用来查看共享标签df1.index & df2.index,但我想将其保留为练习。



 类似资料:
  • 我想我可以做一个逐行和逐列的比较,但有没有更简单的方法?

  • 我想排序2列表并比较它们,但排序方法不起作用。我有2个字符串列表,其中包括整数。 这些是我的名单 我的getwords方法返回:

  • 我有以下课程:

  • 我正在构建一个swing应用程序,它将在左边有一个项目列表,在右边有一个表。右侧显示的表数取决于左侧选择的项。我希望能够“突出显示”(setBackground)显示所有表中相同的所有行。 我读过关于重写prepareRenderer或GetTableCellRendererComponent的文章。然后,条件呈现逻辑位于重写的方法中。 DefaultTableCellRenderer GetTa

  • 问题内容: 我需要比较两个CSV文件并在第三个CSV文件中打印出差异。在我的情况下,第一个CSV是一个名为old.csv的哈希表的旧列表,第二个CSV是包含新旧哈希表的新哈希表。 这是我的代码: 第三个文件是旧文件的副本,而不是更新文件。怎么了 ?我希望你能帮助我,非常感谢! PS:我不想使用diff 问题答案: 问题在于您正在将中的每一行与中的同一行进行比较。只要一个文件中有多余的一行,您就会发

  • 我有两个json字符串,我想比较string2和string1,并打印它们的不同之处。 例如: expectedJson:{Products:{Product:[{Product_name:“string”“unit_cost:“string”}],“Region:[“string”]} inputJson:{Products:{Product:[{Product_name:“string”“un