比较 Pandas DataFrame 对象

Suraj Joshi 2021年1月22日
比较 Pandas DataFrame 对象

本教程介绍了如何在 Python 中比较 Pandas DataFrame 对象。我们可以使用 == 运算符来比较 DataFrame。

import pandas as pd

data_season1 = {"Player": ["Lewandowski", "Haland", "Ronaldo", "Messi", "Mbappe"],
                "Goals": [10, 8, 6, 5, 4]}

data_season2 = {"Player": ["Lewandowski", "Haland", "Ronaldo", "Messi", "Mbappe"],
                "Goals": [7, 8, 6, 7, 4]}

df_1 = pd.DataFrame(data_season1)
df_2 = pd.DataFrame(data_season2)

print("df_1:")
print(df_1)

print("")

print("df_2:")
print(df_2)

输出:

df_1:
        Player  Goals
0  Lewandowski     10
1       Haland      8
2      Ronaldo      6
3        Messi      5
4       Mbappe      4

df_2:
        Player  Goals
0  Lewandowski      7
1       Haland      8
2      Ronaldo      6
3        Messi      7
4       Mbappe      4

在本文中,我们将使用 DataFrame df_1df_2 来演示 DataFrame 的比较。

使用 == 运算符比较 Pandas 的 DataFrame 对象

import pandas as pd

data_season1 = {"Player": ["Lewandowski", "Haland", "Ronaldo", "Messi", "Mbappe"],
                "Goals": [10, 8, 6, 5, 4]}

data_season2 = {"Player": ["Lewandowski", "Haland", "Ronaldo", "Messi", "Mbappe"],
                "Goals": [7, 8, 6, 7, 4]}

df_1 = pd.DataFrame(data_season1)
df_2 = pd.DataFrame(data_season2)

print(df_1 == df_2)

输出:

   Player  Goals
0    True  False
1    True   True
2    True   True
3    True  False
4    True   True

比较 df_1df_2 的对应元素,如果该位置的对应元素相同,则返回 True,否则返回 False

我们可以使用 pandas.DataFrame.all() 方法来知道 df_1df_2 中哪些行是相同的。

import pandas as pd

data_season1 = {"Player": ["Lewandowski", "Haland", "Ronaldo", "Messi", "Mbappe"],
                "Goals": [10, 8, 6, 5, 4]}

data_season2 = {"Player": ["Lewandowski", "Haland", "Ronaldo", "Messi", "Mbappe"],
                "Goals": [7, 8, 6, 7, 4]}

df_1 = pd.DataFrame(data_season1)
df_2 = pd.DataFrame(data_season2)

print((df_1 == df_2).all(axis=1))

输出:

0    False
1     True
2     True
3    False
4     True
dtype: bool

在输出中,值为 True 的行与对应的元素值相同。因此,输出值为 False 的行与对应元素的值不同。

我们可以使用索引来列出所有在 df_1df_2 中值不同的行。

import pandas as pd

data_season1 = {"Player": ["Lewandowski", "Haland", "Ronaldo", "Messi", "Mbappe"],
                "Goals": [10, 8, 6, 5, 4]}

data_season2 = {"Player": ["Lewandowski", "Haland", "Ronaldo", "Messi", "Mbappe"],
                "Goals": [7, 8, 6, 7, 4]}

df_1 = pd.DataFrame(data_season1)
df_2 = pd.DataFrame(data_season2)

print(df_1[(df_1 == df_2).all(axis=1) == False])

输出:

        Player  Goals
0  Lewandowski     10
3        Messi      5

它列出了 df_1 中所有的行,这些行的值与 df_2 中对应的行的值不同。

如果我们对 df_1df_2 有不同的索引,我们会得到一个错误,说 ValueError: Can only compare identically-labeled DataFrame objects

import pandas as pd

data_season1 = {"Player": ["Lewandowski", "Haland", "Ronaldo", "Messi", "Mbappe"],
                "Goals": [10, 8, 6, 5, 4]}

data_season2 = {"Player": ["Lewandowski", "Haland", "Ronaldo", "Messi", "Mbappe"],
                "Goals": [7, 8, 6, 7, 4]}

df_1 = pd.DataFrame(data_season1)
df_2 = pd.DataFrame(data_season2, index=['a', 'b', 'c', 'd', 'e'])

print(df_1 == df_2)

输出:

Traceback (most recent call last):
...
ValueError: Can only compare identically-labeled DataFrame objects

我们可以使用 pandas.DataFrame.reset_index() 方法来重置索引,以克服上述问题。

import pandas as pd

data_season1 = {"Player": ["Lewandowski", "Haland", "Ronaldo", "Messi", "Mbappe"],
                "Goals": [10, 8, 6, 5, 4]}

data_season2 = {"Player": ["Lewandowski", "Haland", "Ronaldo", "Messi", "Mbappe"],
                "Goals": [7, 8, 6, 7, 4]}

df_1 = pd.DataFrame(data_season1)
df_2 = pd.DataFrame(data_season2, index=['a', 'b', 'c', 'd', 'e'])
df_2.reset_index(drop=True, inplace=True)

print(df_1 == df_2)

输出:

   Player  Goals
0    True  False
1    True   True
2    True   True
3    True  False
4    True   True

它在比较 df_1df_2 之前重置了 df_2 的索引,这样两个 DataFrame 就有了相同的索引,使比较成为可能。

在比较它们之前,还必须确保在 DataFrame 中具有相同数量的行。

Author: Suraj Joshi
Suraj Joshi avatar Suraj Joshi avatar

Suraj Joshi is a backend software engineer at Matrice.ai.

LinkedIn

相关文章 - Pandas DataFrame